@xano/sdk 1.0.14 → 1.0.16

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 (290) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +33 -37
  3. package/dist/.build-fingerprint +1 -1
  4. package/dist/{agent-file-refresh-3J6YRVFL.js → agent-file-refresh-DBHTEFYM.js} +12 -12
  5. package/dist/{agent-skill-command-VWDMQWCT.js → agent-skill-command-LHNTU7MH.js} +74 -73
  6. package/dist/{answer-shape-AVZSKBR6.js → answer-shape-ZRQS7ZC4.js} +5 -5
  7. package/dist/{backend-dir-ISP7RVF2.js → backend-dir-AXR43HNV.js} +11 -11
  8. package/dist/{backend-slot-DZAUHLTS.js → backend-slot-7BATLL3X.js} +4 -4
  9. package/dist/bin.js +64 -63
  10. package/dist/{branch-IJTBZZFO.js → branch-SJKKUCMZ.js} +9 -9
  11. package/dist/branch-commands-KGR52SZU.js +80 -0
  12. package/dist/bundle.d.ts +2 -2
  13. package/dist/bundle.js +15 -69
  14. package/dist/{capture-GW5KNKMB.js → capture-RYBJE25P.js} +5 -5
  15. package/dist/{chunk-Z3DQ7ULY.js → chunk-23GEFHRX.js} +236 -17
  16. package/dist/{chunk-3H7R4ISR.js → chunk-2DUYJR5N.js} +2 -2
  17. package/dist/{chunk-MFWF2NZJ.js → chunk-2H5BQRHF.js} +2 -2
  18. package/dist/{chunk-O44MJTLR.js → chunk-35SI4GBM.js} +3 -3
  19. package/dist/{chunk-QKHNJ7LE.js → chunk-3ZV23FVR.js} +5 -5
  20. package/dist/{chunk-HKI5Y5KW.js → chunk-47XIVDJ6.js} +14 -14
  21. package/dist/{chunk-ICK36EGF.js → chunk-4EVDCSEY.js} +2 -2
  22. package/dist/{chunk-FBSGFPZ4.js → chunk-4XGZ325S.js} +3 -3
  23. package/dist/{chunk-EYVIUX2T.js → chunk-4XYXUK5H.js} +76 -33
  24. package/dist/{chunk-MAXDJZQR.js → chunk-4ZBXS7YN.js} +8 -8
  25. package/dist/{chunk-ZMJRAMLA.js → chunk-52QAENY6.js} +14 -14
  26. package/dist/{chunk-2LF734YB.js → chunk-54CJ74BH.js} +4 -4
  27. package/dist/{chunk-3SZ7QRYA.js → chunk-57PGTPT3.js} +8 -8
  28. package/dist/{chunk-IKXXTRMN.js → chunk-64UVVLDT.js} +4 -4
  29. package/dist/{chunk-EQXHUWUO.js → chunk-6FCAFWD5.js} +2 -2
  30. package/dist/{chunk-4MX5LMPQ.js → chunk-6ODQ5GDZ.js} +2 -2
  31. package/dist/{chunk-HK554MDD.js → chunk-74YCPI4G.js} +7 -7
  32. package/dist/{chunk-Y5XAPLZS.js → chunk-7UQZ7C4W.js} +4 -4
  33. package/dist/{chunk-CJDPSCMX.js → chunk-7ZVQIKNL.js} +3 -3
  34. package/dist/{chunk-RVAEPPRH.js → chunk-AICWDCLJ.js} +2 -2
  35. package/dist/{chunk-WS4BA75E.js → chunk-AJBOGO5U.js} +4 -4
  36. package/dist/{chunk-2FDHIBEU.js → chunk-AJQFUJEQ.js} +8 -8
  37. package/dist/{chunk-2KOB4QPW.js → chunk-C7AYP4H6.js} +29 -20
  38. package/dist/{chunk-XCFQLP6G.js → chunk-DJMGDCVX.js} +8 -8
  39. package/dist/{chunk-VBSCWV5H.js → chunk-DLD4FVRP.js} +54 -54
  40. package/dist/{chunk-Q7DGTQ5G.js → chunk-E34VGSCI.js} +2 -1
  41. package/dist/{chunk-YR3MNGWZ.js → chunk-E5M5P23K.js} +8 -8
  42. package/dist/{chunk-HJZUI2ZU.js → chunk-EAZTRU75.js} +2 -2
  43. package/dist/{chunk-QX5XQEYB.js → chunk-EINZSVEU.js} +5 -5
  44. package/dist/{chunk-KMKUH2IO.js → chunk-EPB6FAR5.js} +5 -5
  45. package/dist/chunk-EUAU4QKI.js +67 -0
  46. package/dist/{chunk-IDOVZLPK.js → chunk-EXJ4Q5F6.js} +2 -2
  47. package/dist/{chunk-IHL2O7VY.js → chunk-F3JK5RIY.js} +3 -2
  48. package/dist/{chunk-W2QFR3ZJ.js → chunk-FIOC7RSU.js} +2 -2
  49. package/dist/{chunk-YEH5OIPF.js → chunk-FMXPV5JI.js} +39 -11
  50. package/dist/{chunk-GVHWIDEJ.js → chunk-FRJB3NTE.js} +10 -5
  51. package/dist/{chunk-VIRFG3WG.js → chunk-FTFAPKCW.js} +23 -7
  52. package/dist/{chunk-LL6ED5IB.js → chunk-FTS42N37.js} +2 -2
  53. package/dist/{chunk-MIS6F4HM.js → chunk-G2XSDIYS.js} +4 -4
  54. package/dist/{chunk-ZY55DO5P.js → chunk-G6BEJ3NA.js} +2 -2
  55. package/dist/{chunk-RYWNNJK5.js → chunk-GA6HTO3O.js} +2 -2
  56. package/dist/{chunk-JIKGT7DO.js → chunk-GE3JV5SI.js} +1 -1
  57. package/dist/{chunk-GCINMMFL.js → chunk-GJZMKMWO.js} +2 -2
  58. package/dist/{chunk-LW7TOIS7.js → chunk-GRZ62LLU.js} +8 -8
  59. package/dist/{chunk-6X73VFCX.js → chunk-GT7PZCTK.js} +2 -2
  60. package/dist/{chunk-HINRE3UM.js → chunk-HXPQXCOZ.js} +1821 -506
  61. package/dist/{chunk-ECQXASG3.js → chunk-IFHFJR5O.js} +2 -2
  62. package/dist/{chunk-P4OWRYE7.js → chunk-IOWNQEMW.js} +31 -31
  63. package/dist/{chunk-SUKO4SZG.js → chunk-ISIZFK5Q.js} +53 -47
  64. package/dist/{chunk-QJ25N4W6.js → chunk-IUJDUFT7.js} +4 -4
  65. package/dist/{chunk-L34DM6QB.js → chunk-JHAZK4RY.js} +3 -3
  66. package/dist/{chunk-YL3WVBR5.js → chunk-KGHJ74HF.js} +6 -6
  67. package/dist/{chunk-NUZXSIEA.js → chunk-L2O5KG5Q.js} +6 -6
  68. package/dist/{chunk-L4WG4BKJ.js → chunk-L3Q2QYIQ.js} +72 -72
  69. package/dist/{chunk-SAEIVQLP.js → chunk-LLBEPJBO.js} +3 -3
  70. package/dist/{chunk-NOW522B4.js → chunk-LWBGPPI5.js} +13 -13
  71. package/dist/{chunk-GOKRKTCX.js → chunk-MBSHONP3.js} +3 -3
  72. package/dist/{chunk-GKQTXUOW.js → chunk-MOVRSULZ.js} +2 -2
  73. package/dist/{chunk-QAEBBTYR.js → chunk-MSYMEP7Y.js} +7 -7
  74. package/dist/{chunk-Y453TW6J.js → chunk-NCERS5QH.js} +2 -2
  75. package/dist/{chunk-HXFLHA5K.js → chunk-NH5Z2NOD.js} +2 -2
  76. package/dist/{chunk-T3HNISBN.js → chunk-NJVY3GAX.js} +3 -3
  77. package/dist/{chunk-J62TYONQ.js → chunk-NQPPUNWP.js} +3 -3
  78. package/dist/{chunk-LJZIBT75.js → chunk-O7Z3LF44.js} +5 -5
  79. package/dist/{chunk-B7CPSWQX.js → chunk-OLXYZQR7.js} +7 -7
  80. package/dist/{chunk-7F3V6CFP.js → chunk-OQNYZ2OM.js} +3 -3
  81. package/dist/{chunk-DBDTQR23.js → chunk-OTQF4B37.js} +4 -4
  82. package/dist/{chunk-GBSHHNSD.js → chunk-PRSNMSVG.js} +3 -3
  83. package/dist/{chunk-DGYXCIBV.js → chunk-Q6AKSLD2.js} +2 -2
  84. package/dist/{chunk-YTQYP7UJ.js → chunk-Q7KXMIR3.js} +3 -3
  85. package/dist/{chunk-IWJ6GFST.js → chunk-QCVH32T2.js} +5 -5
  86. package/dist/{chunk-7FIMUFBP.js → chunk-QDPY7RN3.js} +3 -3
  87. package/dist/{chunk-DLDYQNGP.js → chunk-QIT2GGNB.js} +3 -3
  88. package/dist/{chunk-J3XLCYTQ.js → chunk-QSJH5AFU.js} +244 -173
  89. package/dist/{chunk-DERQSEB5.js → chunk-R7DS2TRZ.js} +38 -22
  90. package/dist/{chunk-BEKEOXNG.js → chunk-RGPHFHJU.js} +2 -2
  91. package/dist/{chunk-5FJ4M4HB.js → chunk-RHH6SCB4.js} +17 -32
  92. package/dist/{chunk-Z4BQPABS.js → chunk-RIT3WBBX.js} +4 -4
  93. package/dist/{chunk-45K2QZBR.js → chunk-RKNCISPM.js} +3 -3
  94. package/dist/{chunk-6LJS4M6P.js → chunk-RKTVXFBV.js} +5 -5
  95. package/dist/{chunk-AXNX4NWN.js → chunk-RLQX6LHW.js} +37 -37
  96. package/dist/{chunk-FIERONKM.js → chunk-ROWYW3JF.js} +2 -2
  97. package/dist/{chunk-LSJ3SQEU.js → chunk-RVWWNNZQ.js} +4 -4
  98. package/dist/{chunk-LPQZICYN.js → chunk-S7MVI4W7.js} +7 -7
  99. package/dist/{chunk-4MIV244X.js → chunk-SGEOXJIH.js} +9 -2
  100. package/dist/{chunk-QRMKQYCB.js → chunk-SINL5WMI.js} +2 -2
  101. package/dist/{chunk-Z6N5N4MN.js → chunk-SIW2HT2H.js} +21 -5
  102. package/dist/{chunk-IEDQT4Z3.js → chunk-SOAZIMWL.js} +12 -12
  103. package/dist/{chunk-RPBB7P4Q.js → chunk-SVQMDVND.js} +87 -16
  104. package/dist/{chunk-45ZUMF4E.js → chunk-TPUAXIPR.js} +2 -2
  105. package/dist/{chunk-HMYJOQXT.js → chunk-TXU34ELY.js} +25 -25
  106. package/dist/{chunk-MTBKTGZT.js → chunk-U4UAWGIT.js} +12 -8
  107. package/dist/{chunk-76SBT7KS.js → chunk-U56HK2RG.js} +7 -5
  108. package/dist/{chunk-RV2BDU7V.js → chunk-UDW2KAVF.js} +6 -6
  109. package/dist/{chunk-NDV6CBR7.js → chunk-UH5VQGNR.js} +2 -2
  110. package/dist/{chunk-75QC66XI.js → chunk-V2MIBJZU.js} +2 -2
  111. package/dist/{chunk-RDZBXTZ3.js → chunk-VAQPQXOI.js} +4 -4
  112. package/dist/{chunk-XPSDDTUZ.js → chunk-VCFRALU7.js} +3 -3
  113. package/dist/{chunk-5KJBWIDZ.js → chunk-VQDVEHDB.js} +2 -2
  114. package/dist/{chunk-6ILHYSLR.js → chunk-WAP5362D.js} +5 -5
  115. package/dist/{chunk-XY4OBD26.js → chunk-WGKKDGSA.js} +4 -4
  116. package/dist/{chunk-UQ2OD7D4.js → chunk-WVVUE7LU.js} +14 -7
  117. package/dist/{chunk-LB76VK6D.js → chunk-WXQ7BHVQ.js} +7 -7
  118. package/dist/{chunk-7REDHC4N.js → chunk-X5NF3ZXW.js} +69 -14
  119. package/dist/{chunk-5W7S2SCA.js → chunk-XAE4NIZ2.js} +4 -4
  120. package/dist/{chunk-SPLRKCFV.js → chunk-XDGLYIB2.js} +2 -2
  121. package/dist/{chunk-BSGU4HS6.js → chunk-XKMZYU5B.js} +96 -65
  122. package/dist/{chunk-OLQN4Z5R.js → chunk-Y3RH35KM.js} +47 -47
  123. package/dist/{chunk-YFQCDLCQ.js → chunk-YHT7TDSH.js} +14 -14
  124. package/dist/{chunk-KDEU5FUJ.js → chunk-YJXJOMXW.js} +3 -3
  125. package/dist/{chunk-N6LGLNAC.js → chunk-YPLHVRMS.js} +4 -4
  126. package/dist/{chunk-WS2X5BB2.js → chunk-YYBBJPCL.js} +5 -5
  127. package/dist/{chunk-ZOHEHIFS.js → chunk-YYDM4DNP.js} +2 -2
  128. package/dist/{chunk-MYIIBV6A.js → chunk-ZF4LCHCT.js} +5 -5
  129. package/dist/{chunk-GRXX2TOJ.js → chunk-ZHFSIQ6E.js} +2 -2
  130. package/dist/{chunk-CB67GIR3.js → chunk-ZJQFKBX7.js} +7 -7
  131. package/dist/{chunk-ZRXDPCMN.js → chunk-ZYZ7GRX3.js} +2 -2
  132. package/dist/{chunk-5TWLVFYB.js → chunk-ZZC5VSLP.js} +4 -4
  133. package/dist/cli.d.ts +3 -3
  134. package/dist/cli.js +62 -61
  135. package/dist/codegen-command-NAY6YAOD.js +183 -0
  136. package/dist/codegen.d.ts +3 -3
  137. package/dist/codegen.js +5 -5
  138. package/dist/{commands-5ILSWDSV.js → commands-Z2QZOORB.js} +3 -3
  139. package/dist/{completion-UNKBVVDT.js → completion-LFXXNQGR.js} +3 -3
  140. package/dist/{config-NTOASFCA.js → config-7GGINOFY.js} +4 -4
  141. package/dist/{deploy-command-WESYWFJN.js → deploy-command-PBM3S4ZL.js} +69 -68
  142. package/dist/{deploy-source-ZQQNMDFX.js → deploy-source-JW7DAN75.js} +32 -32
  143. package/dist/{dev-env-sync-4XJT7WOT.js → dev-env-sync-FHJTFH3V.js} +63 -62
  144. package/dist/{diagnostics-FNVNRYMB.js → diagnostics-T3RN3372.js} +2 -2
  145. package/dist/{display-name-hint-MYXCCAOP.js → display-name-hint-5GLJGPQ6.js} +11 -11
  146. package/dist/{emit-YLt3GfsZ.d.ts → emit-t-gDE1BL.d.ts} +181 -93
  147. package/dist/env-example-refresh-HHEGMFNH.js +136 -0
  148. package/dist/{env-pull-command-SK5FS477.js → env-pull-command-FFPNRVWD.js} +52 -52
  149. package/dist/{env-target-TEFSYACA.js → env-target-XHVRZXHX.js} +14 -14
  150. package/dist/{env-var-command-IJHKA2WJ.js → env-var-command-DJS62YRR.js} +41 -41
  151. package/dist/{ephemeral-VLPRDNEJ.js → ephemeral-2DXWP3VK.js} +9 -9
  152. package/dist/{ephemeral-command-WCO5J4SN.js → ephemeral-command-VLQIQ5TS.js} +52 -52
  153. package/dist/{ephemeral-state-RUOU2GFS.js → ephemeral-state-56XEDUJW.js} +12 -12
  154. package/dist/{generate-command-3WCOUOEQ.js → generate-command-PSDIIOTU.js} +89 -88
  155. package/dist/{gitignore-WYS3GMOX.js → gitignore-PMJ6MFNA.js} +15 -15
  156. package/dist/{guards-PPIBIMFZ.js → guards-YICHJKX3.js} +51 -15
  157. package/dist/{impersonate-command-UMYVQTCG.js → impersonate-command-IKV4KUYA.js} +37 -37
  158. package/dist/{import-T4ZTOTBT.js → import-VJQGIS33.js} +5 -5
  159. package/dist/index.d.ts +653 -222
  160. package/dist/index.js +29 -28
  161. package/dist/init-command-LEQIE6GC.js +143 -0
  162. package/dist/{init-modules-7KALFI5C.js → init-modules-G47Q7ABV.js} +8 -8
  163. package/dist/{init-web-DYE2FEXL.js → init-web-25QJ4JWB.js} +3 -3
  164. package/dist/internal.d.ts +55 -8
  165. package/dist/internal.js +692 -503
  166. package/dist/{io-PGTCBSIQ.js → io-47TFRYDB.js} +6 -6
  167. package/dist/{keep-data-merge-OVHCIEBG.js → keep-data-merge-XCPCX7BZ.js} +38 -38
  168. package/dist/{lambda-config-reconcile-VOBVZPWS.js → lambda-config-reconcile-CC5QIP6E.js} +3 -3
  169. package/dist/{landed-F7PCHGCK.js → landed-VIUFHLCJ.js} +5 -5
  170. package/dist/{landing-record-AIHNW4AZ.js → landing-record-JQ7HZDGI.js} +22 -22
  171. package/dist/{live-diff-UMSOGPX3.js → live-diff-KJ2TWWWT.js} +14 -14
  172. package/dist/{local-engine-choice-XDGTATKJ.js → local-engine-choice-DFAMYOIF.js} +35 -35
  173. package/dist/{local-engine-command-VQWNQ7UK.js → local-engine-command-5RP2J5QZ.js} +40 -40
  174. package/dist/{local-engine-deploy-4N4NFZ4T.js → local-engine-deploy-XAEDT55W.js} +12 -12
  175. package/dist/{local-engine-lookup-AQTUGSBT.js → local-engine-lookup-WBYTY2JE.js} +2 -2
  176. package/dist/{local-engine-mcp-bridge-AMYRH4SY.js → local-engine-mcp-bridge-3H5OXBWQ.js} +5 -5
  177. package/dist/{local-engine-mcp-command-AIMNMXQG.js → local-engine-mcp-command-JSYVVZKK.js} +42 -42
  178. package/dist/{local-engine-process-OD5OSWDG.js → local-engine-process-35B2KQED.js} +7 -7
  179. package/dist/{local-engine-update-check-G3YCBXRE.js → local-engine-update-check-VXJZSIJU.js} +5 -5
  180. package/dist/{lock-HDCHD2ON.js → lock-JBKTDEDO.js} +4 -4
  181. package/dist/{lock-commands-H3YV2D6M.js → lock-commands-7VO6YWOV.js} +67 -66
  182. package/dist/{login-command-NMM3JNDZ.js → login-command-WTZUBCW6.js} +27 -27
  183. package/dist/{logout-command-7DYC6G32.js → logout-command-5BJUNK3C.js} +17 -17
  184. package/dist/{loop-DJNIHC7O.js → loop-HILLODVH.js} +15 -15
  185. package/dist/{marketplace-command-UCSHDZGO.js → marketplace-command-NMOH4XOV.js} +30 -30
  186. package/dist/{marketplace-resolve-JR4BBJ6K.js → marketplace-resolve-63QWMQZU.js} +6 -6
  187. package/dist/{meta-client-CD3TXQP6.js → meta-client-MRAMWUKV.js} +15 -15
  188. package/dist/{module-manifest-63I5GRK4.js → module-manifest-NWJWAQLQ.js} +4 -4
  189. package/dist/node.d.ts +8 -8
  190. package/dist/node.js +71 -70
  191. package/dist/{operation-outcome-2ONIIDRU.js → operation-outcome-WK7UW6PJ.js} +24 -24
  192. package/dist/{output-target-67LHZKCO.js → output-target-5PYRCCK4.js} +16 -16
  193. package/dist/{plan-disclosure-T7DF4SRJ.js → plan-disclosure-6MG4YYJV.js} +28 -28
  194. package/dist/{plugin-contributions-YYEP7IWH.js → plugin-contributions-DD6R6RL6.js} +5 -5
  195. package/dist/{plugin-prompt-GKCQKNYI.js → plugin-prompt-UX2TT5NS.js} +5 -5
  196. package/dist/{plugin-questions-P7MA3TYI.js → plugin-questions-WE2F4ZC4.js} +4 -4
  197. package/dist/{preflight-command-TJ7FURXB.js → preflight-command-3BX2WW3S.js} +75 -74
  198. package/dist/{profile-command-LDPLTJEJ.js → profile-command-GSUX3UMB.js} +28 -28
  199. package/dist/{profile-pointer-JJ7K5O2R.js → profile-pointer-RCPHVTJV.js} +4 -4
  200. package/dist/{project-dependency-X3KCWBK5.js → project-dependency-TPVV3YIX.js} +7 -7
  201. package/dist/{project-sdk-YHJZRCNB.js → project-sdk-DKZBK5H5.js} +4 -4
  202. package/dist/promote-command-3LQTXWCD.js +149 -0
  203. package/dist/{prompt-QNMJIWNI.js → prompt-OYQHQWKI.js} +4 -4
  204. package/dist/{publish-command-IIRN6NWN.js → publish-command-3BQCV4NE.js} +72 -71
  205. package/dist/pull-command-B7OVWTZD.js +171 -0
  206. package/dist/{pull-superseded-6HADGGC5.js → pull-superseded-3SSM3JFT.js} +4 -4
  207. package/dist/{raw-where-gWGr-E4t.d.ts → raw-where-CinW0keO.d.ts} +32 -4
  208. package/dist/release-command-XSDICMJE.js +153 -0
  209. package/dist/{release-ns-command-YLCQPVH3.js → release-ns-command-EVAHK4CU.js} +96 -95
  210. package/dist/{retry-command-LFZYEVRU.js → retry-command-WP4ZI6CJ.js} +8 -8
  211. package/dist/{routes-manifest-R3TQRB24.js → routes-manifest-N73THJB3.js} +16 -16
  212. package/dist/routes-manifest-file-LDUDIVFJ.js +41 -0
  213. package/dist/scaffold.js +2 -2
  214. package/dist/{secrets-file-PCNAFXNV.js → secrets-file-7XWR7HW3.js} +15 -15
  215. package/dist/{secrets-fill-command-G7NQMRXU.js → secrets-fill-command-NKCGC75L.js} +66 -65
  216. package/dist/{seed-4CD55LB4.js → seed-YKTZDS2Q.js} +13 -13
  217. package/dist/{source-resolve-U4SJR7ZA.js → source-resolve-CQGDFQQC.js} +22 -22
  218. package/dist/{static-host-MO4VDHL7.js → static-host-3HPZKVKK.js} +5 -5
  219. package/dist/{status-command-CD72PXIT.js → status-command-TBMQ3GJP.js} +38 -38
  220. package/dist/{store-AJX4MC7Y.js → store-B63BQV6R.js} +6 -6
  221. package/dist/{store-BM7SQcUt.d.ts → store-in7gSpMS.d.ts} +297 -129
  222. package/dist/sync-baseline-GRS33AB5.js +38 -0
  223. package/dist/{sync-contributions-XK6LHISZ.js → sync-contributions-RKPLZPPO.js} +9 -9
  224. package/dist/{sync-record-NE62ERA3.js → sync-record-AWFCSS4D.js} +15 -15
  225. package/dist/{table-WPRAM4VW.js → table-ONGT3JGE.js} +12 -12
  226. package/dist/{tables-command-NMTKR52H.js → tables-command-UYQ277TJ.js} +41 -41
  227. package/dist/{tenant-IIYECNWO.js → tenant-IXIW3FOI.js} +10 -10
  228. package/dist/{tenant-command-XQAWT46C.js → tenant-command-7LWZUK2V.js} +104 -103
  229. package/dist/{test-command-W4AD4KT4.js → test-command-7KTT5EAF.js} +56 -45
  230. package/dist/{tests-JWQRHFCT.js → tests-N4MMBABH.js} +6 -6
  231. package/dist/{token-P3VQ6ITJ.js → token-3TCMW2AP.js} +13 -13
  232. package/dist/{toolchain-hooks-UAJBPSTC.js → toolchain-hooks-IJWV3ZQS.js} +18 -18
  233. package/dist/{toolchain-modules-S3MPHCUI.js → toolchain-modules-PBVBCPQJ.js} +5 -5
  234. package/dist/{toolchain-peers-FQJBTKEB.js → toolchain-peers-EMOYN4U7.js} +8 -8
  235. package/dist/{tracked-backend-WWEPNUD5.js → tracked-backend-YDUUQZQF.js} +34 -34
  236. package/dist/update-check-C6KDFGMT.js +141 -0
  237. package/dist/{upgrade-command-J6LRNHYF.js → upgrade-command-ZSBTSMBR.js} +68 -67
  238. package/dist/{whoami-command-KWRP2CII.js → whoami-command-L6ERHR5K.js} +16 -16
  239. package/dist/{workspace-3YNK4XO4.js → workspace-5DPSDM4A.js} +5 -5
  240. package/dist/{workspace-binding-TTDNXHO5.js → workspace-binding-MVOWGNYW.js} +15 -15
  241. package/dist/{workspace-command-W4ANGLCZ.js → workspace-command-PKQ5TDR7.js} +100 -99
  242. package/dist/{workspace-env-6LJGCTZA.js → workspace-env-UZJZUIYV.js} +18 -12
  243. package/dist/{workspace-export-PUEXKZNS.js → workspace-export-3KMWNZDD.js} +5 -5
  244. package/dist/{writable-LMMG4AFZ.js → writable-X7BCN7XE.js} +4 -4
  245. package/dist/xano-YB6Y2IJS.js +44 -0
  246. package/dist/{xanosdk-import-PNNMZ4SF.js → xanosdk-import-HHMQDK2I.js} +10 -10
  247. package/dist/{xanosdk-project-YW3BQY2E.js → xanosdk-project-CKEUNJU4.js} +13 -13
  248. package/dist/{xdo-D4OwfF2J.d.ts → xdo-DNGZGO1j.d.ts} +50 -12
  249. package/guides/authoring.md +1 -0
  250. package/guides/codes.md +33 -3
  251. package/guides/coverage.md +2 -2
  252. package/guides/object-kinds.md +1 -1
  253. package/guides/typed-frontend.md +9 -0
  254. package/llms/client.md +54 -36
  255. package/llms/errors.md +26 -6
  256. package/llms/fields.md +53 -30
  257. package/llms/filters.md +55 -46
  258. package/llms/kinds-agent-mcp.md +10 -9
  259. package/llms/kinds-core.md +19 -15
  260. package/llms/kinds-knowledge.md +4 -4
  261. package/llms/kinds-realtime.md +25 -23
  262. package/llms/lambda.md +42 -30
  263. package/llms/legacy.md +6 -7
  264. package/llms/lock.md +21 -17
  265. package/llms/object-kinds.md +9 -11
  266. package/llms/statements-calls.md +41 -20
  267. package/llms/statements-catalog.md +78 -71
  268. package/llms/statements-data.md +35 -25
  269. package/llms/statements-runtime.md +28 -18
  270. package/llms/tests.md +20 -7
  271. package/llms/toolchain.md +12 -9
  272. package/llms/triggers.md +14 -18
  273. package/llms/values.md +16 -9
  274. package/llms-full.txt +689 -549
  275. package/llms.txt +120 -137
  276. package/manifest.json +228 -246
  277. package/package.json +1 -1
  278. package/skills/xano-backend/SKILL.md +10 -12
  279. package/types/lambda-globals.d.ts +6 -1
  280. package/dist/branch-commands-75IYFTBS.js +0 -80
  281. package/dist/codegen-command-JWOW6HE5.js +0 -182
  282. package/dist/env-example-refresh-4V2OCDJE.js +0 -135
  283. package/dist/init-command-UR5MSXIH.js +0 -142
  284. package/dist/promote-command-RURHOLNR.js +0 -148
  285. package/dist/pull-command-ITO76ENU.js +0 -170
  286. package/dist/release-command-CVGIUD4M.js +0 -152
  287. package/dist/routes-manifest-file-GYNYFKAH.js +0 -41
  288. package/dist/sync-baseline-BJDKG4F2.js +0 -38
  289. package/dist/update-check-O7QC5TBB.js +0 -140
  290. package/dist/xano-Z3SRHYOR.js +0 -43
package/llms-full.txt CHANGED
@@ -1,4 +1,4 @@
1
- # xanosdk v1.0.14
1
+ # xanosdk v1.0.16
2
2
 
3
3
  > TypeScript SDK that compiles a typed Xano workspace into the importable packageExport JSON bundle.
4
4
 
@@ -16,21 +16,18 @@ TAGGED value — `ref("x")` a stack variable, `inp("x")` an input, `auth("id")`
16
16
  caller, `c.*` a constant — resolved at request time; JS operators over them do not
17
17
  compute (see Gotchas). Requests share no memory — state persists in tables or redis.
18
18
 
19
- Authorable: statement surfaces 218/218, filters 246 (246 typed).
20
- Not authorable here: branch, market_item, realtime_channel, run.job, run.service, tablemap — these cannot be authored and do not survive a pull; reasons in `coverage.objectKinds.unmodeled`.
21
-
22
- This file is the whole always-read surface: the mental model, the deploy contract,
23
- every cross-cutting gotcha, and control flow. Per-surface detail lives in the topic files listed
24
- below — open the one whose condition matches the task, skip the rest. For
25
- exhaustive per-entry detail in NEITHER — a statement's field schema with engine
26
- defaults, a filter's full argument list, the `storedName` mapping — do a TARGETED
27
- lookup in the shipped `manifest.json` (a program imports it as
28
- `@xano/sdk/manifest.json`, needing `with { type: "json" }` in Node ESM;
29
- it is ~70k tokens, so never read it whole). Its top-level keys are `name`, `version`, `description`, `coverage`, `values`, `objectKinds`, `fieldTypes`, `statements`, `filters`, `cli`, `cliGlobalFlags`. `statements` and `filters` are ARRAYS, not maps — SELECT, do not index:
19
+ Authorable: statement surfaces 219/219, filters 246 (246 typed).
20
+ Not authorable here: branch, market_item, realtime_channel (legacy; author realtimeServer + realtimeChannel instead), run.job, run.service, tablemap — these cannot be authored and do not survive a pull; reasons in `coverage.objectKinds.unmodeled`.
21
+
22
+ Per-surface detail is in the topic files below: open the one whose condition matches the task.
23
+ Per-entry detail (a statement's field schema with engine defaults, a filter's full argument
24
+ list, the `storedName` mapping) is in the shipped `manifest.json` — do a TARGETED lookup;
25
+ it is ~70k tokens, so never read it whole. A program imports it as `@xano/sdk/manifest.json`
26
+ (Node ESM needs `with { type: "json" }`). Its top-level keys are `name`, `version`, `description`, `coverage`, `values`, `objectKinds`, `fieldTypes`, `statements`, `filters`, `cli`, `cliGlobalFlags`. `statements` and `filters` are ARRAYS, not maps — SELECT, do not index:
30
27
  jq '.statements[] | select(.sPath=="db.get")' manifest.json
31
28
  jq '.filters[] | select(.name=="json_decode")' manifest.json
32
- ⚠ `fields` is null on the 65 `declarative: false` statements (`db.get`, …): typed wrappers whose arguments are the factory's `.d.ts` signature. Null ≠ missing.
33
- Select a statement on `sPath` (the `s.*` path you write), NOT `surface` (the XanoScript term): 24 of 218 differ — `var`→`set_var`, `break`→`foreach_break`, `foreach.remove`→`foreach_remove`, and every `expect.*`.
29
+ ⚠ `fields` is null on the 66 `declarative: false` statements (`db.get`, …): typed wrappers whose arguments are the factory's `.d.ts` signature. Null ≠ missing.
30
+ Select a statement on `sPath` (the `s.*` path you write), NOT `surface` (the XanoScript term): 24 of 219 differ — `var`→`set_var`, `break`→`foreach_break`, `foreach.remove`→`foreach_remove`, and every `expect.*`.
34
31
 
35
32
  ## Topic files
36
33
 
@@ -61,9 +58,6 @@ plain file read resolves them at the version you have.
61
58
 
62
59
  ## Quickstart
63
60
 
64
- Authoring is **declarative def-objects** passed to factories — there is no
65
- callback/chaining builder.
66
-
67
61
  ```ts
68
62
  import { workspace, apiGroup, query, table, input, f, ref, inp, auth, s } from "@xano/sdk";
69
63
 
@@ -72,13 +66,13 @@ const users = table({
72
66
  auth: true, // backs authentication
73
67
  // `id` (int PK) + `created_at` (epochms) are auto-injected — don't declare them.
74
68
  schema: {
75
- email: f.email({ required: true }),
69
+ email: f.email({ required: true, methods: ["trim", "lower"] }), // a unique email index is CASE-SENSITIVE — lowercase it
76
70
  name: f.text(),
77
71
  },
78
72
  // Indexes: { type, fields: [{ name, op? }] }. `"unique"` is shorthand for `"btree|unique"`.
79
73
  // A DOTTED name indexes a key inside a column (`xdo.email`); only the part before the
80
74
  // first dot is checked against the schema.
81
- index: [{ type: "unique", fields: [{ name: "email" }] }], // also: btree, hash, gin, search, gist, vector
75
+ index: [{ type: "unique", fields: [{ name: "email" }] }],
82
76
  });
83
77
 
84
78
  const posts = table({
@@ -119,30 +113,26 @@ package.json or name the entry `.mts`. `npm init -y` writes `"type": "commonjs"`
119
113
  which fails with a "must be ES modules" error until you switch it to module.
120
114
 
121
115
  Set `canonical` on every `apiGroup`. The engine mints the URL token server-side, so
122
- without one a group's client paths are unresolvable until a lock exists: the bundle
123
- exports fine and `npx @xano/sdk routes` / `getPath()` then fail on the very queries it just
124
- built. An explicit `canonical` resolves them from the source alone.
125
- ⚠ A canonical is unique across the whole INSTANCE, not per workspace — two
126
- workspaces cannot serve the same one, and no flag shares it. One set in code is a PIN:
127
- a merge refuses (exit 2) when another workspace holds it. One the lock minted is a
128
- preference the instance may keep or replace with a random token, and `--static` is
129
- refused when it does.
130
-
131
- Build warnings: `export()` prints the shapes that deploy clean and then do the wrong
132
- thing (a `bulk.update` zero-filling omitted columns, an `ignoreEmpty` on an empty
133
- operand, a `ref()` nothing binds). Each has a legitimate use, so each only warns —
134
- but nothing fails on a message no one reads, so in CI and in unattended agent builds
135
- pass `--strict` (`emitBundle(app, { strict: true })` / `app.export({ strict: true })`):
136
- every warning becomes a hard failure. Same bundle bytes either way.
116
+ without one `npx @xano/sdk routes` / `getPath()` cannot resolve the group's paths until a
117
+ lock exists (the export itself succeeds).
118
+ ⚠ A canonical is unique across the whole INSTANCE, not per workspace; no flag shares one.
119
+ A canonical set in code is a PIN: a merge refuses (exit 2) when another workspace holds it.
120
+ One only the lock minted is not pinned: the instance may replace it with a random token,
121
+ and `--static` is refused when it does.
122
+
123
+ Build warnings: `export()` warns on shapes that deploy but misbehave (a `bulk.update`
124
+ zero-filling omitted columns, an `ignoreEmpty` on an empty operand, a `ref()` nothing
125
+ binds). In CI and agent builds pass `--strict` (`emitBundle(app, { strict: true })` /
126
+ `app.export({ strict: true })`): every warning becomes a hard failure. Same bundle bytes
127
+ either way.
137
128
  Before calling the work done: `npm run typecheck`, `npx @xano/sdk export <entry> --strict`,
138
129
  `deploy <entry>`, then `test run-all` against what deployed.
139
130
 
140
- Identity: object guids derive from `(type, name)` — a query's from `(api group,
141
- verb, name)` — so renames change identity.
142
- EVERY build freezes every guid + api-group/toolset canonical in a lock file
143
- BESIDE THE ENTRY FILE — `xano/xano.lock` for the standard scaffold,
144
- NOT the project root — which you COMMIT (`--no-lock` opts out; CI guard
145
- `--frozen-lock` fails instead of changing it).
131
+ Identity: object guids derive from `(type, name)` (a query adds group + verb),
132
+ so renames change identity.
133
+ Every build freezes every guid + api-group/toolset canonical in a lock file beside the entry
134
+ file (`xano/xano.lock` in the standard scaffold, not the project root). Commit it
135
+ (`--no-lock` opts out; CI guard `--frozen-lock` fails instead of changing it).
146
136
  To rename an object: rename in code, export (stderr prints the exact fix-up), run
147
137
  `npx @xano/sdk lock rename <kind> <old> <new>`, export again — the original guid is emitted
148
138
  under the new name, so the engine renames in place instead of delete+create. Taking
@@ -156,51 +146,58 @@ Commands here run as `npx @xano/sdk <cmd>`: `init` → `deploy` → URL. A deplo
156
146
  `export` (honoring `xano.lock`), imports the result, and prints the URL.
157
147
  ⚠ Every deploy is a FULL REPLACE of its destination — objects AND records.
158
148
 
159
- **Backends** — one grammar: `workspace` | `ephemeral[:<name>]` | `local[:<name>]`
160
- (no credential) | `tenant:<name>` | `release:<name>` | a bundle path where a file fits. Reads
161
- `--from`, writes `--to`, `test --on`; positional on `deploy`/`pull`/`generate`/`tables`/
162
- `impersonate`. Omitted = the ephemeral or Xano Engine this project last deployed to, never
163
- workspace/tenant; bare `deploy` compiles onto the Xano Engine instead (`--ephemeral`: an
164
- ephemeral), and `generate`/`init --from` need one. A refusal, typed or tracked,
165
- names the reason and the spellings (`release create` refuses a Xano Engine).
166
- `release create --from` records a run: no bundle path, no `release:`,
167
- and a `tenant:` only if throwaway (`standard`/`run` refused).
149
+ **Backends** — one grammar for every command that names a backend:
150
+
151
+ - Spellings: `workspace` | `ephemeral[:<name>]` | `local[:<name>]` (no credential) |
152
+ `tenant:<name>` | `release:<name>` | a bundle path where a file fits.
153
+ - Reads `--from`, writes `--to`, `test --on`; positional on `deploy`/`pull`/`generate`/`tables`/
154
+ `impersonate`.
155
+ - Omitted = the ephemeral or Xano Engine this project last deployed to, never
156
+ workspace/tenant. Exceptions: bare `deploy` always targets the Xano Engine (`--ephemeral`: an
157
+ ephemeral); `generate`/`init --from` need one.
158
+ - A backend a command cannot serve is refused, typed or tracked, with the reason and the valid
159
+ spellings (`release create` refuses a Xano Engine).
160
+ - `release create --from` takes a run only: no bundle path, no `release:`, and a
161
+ `tenant:` only if throwaway (`standard`/`run` refused).
168
162
 
169
163
  **Destinations** — the Xano Engine by default, real only when you say so:
170
164
 
171
- - `deploy [source]` → the Xano Engine on this machine (no account). `--ephemeral` → a NAMED, auto-expiring ephemeral (~1h; `--expires-hours`
172
- 1–24), tracked in `./.xano/ephemeral.json`, so deploying again REFRESHES it at the same
173
- URL; if it expired or was swept, a fresh one is created and the new URL called out.
174
- ⚠ Only the BACKEND URL survives a refresh — the replace clears static hosting, so
175
- `--static` publishes a NEW host every run and the previous URL stops serving
176
- (not under `--keep-data`, which MERGES an env a deploy filled: rows kept, no re-seed,
177
- removed objects deleted; ⚠ a rename loses values, a RETYPE reads unfit ones as null, env
178
- VALUES are not applied, a table trigger refuses it — `--reset` replaces and re-seeds).
179
- - `release create <name>` cuts from a running source and LANDS in your workspace
180
- — the record that it came up, and the only thing `promote`/`tenant deploy` take. A
181
- taken name is refused, and so is one that addresses a LOCATION instead of naming: `/`,
182
- `\`, `:`, or a leading `.`. Every export derives its FILENAME from the name it is given,
183
- so `release|ephemeral|workspace export` refuse those same shapes unless `--path` names
184
- the file. Carries EVERY table's SCHEMA either way; `--seed[=<guids>]` adds
185
- ROWS — guids from `tables <backend>`; a redeploy KEEPS them.
165
+ - `deploy [source]` → the Xano Engine on this machine (no account).
166
+ - `--ephemeral` → a NAMED, auto-expiring ephemeral (~1h; `--expires-hours` 1–24), tracked in
167
+ `./.xano/ephemeral.json`, so deploying again REFRESHES it at the same URL; if it expired or
168
+ was swept, a fresh one is created and the new URL printed.
169
+ - ⚠ Only the BACKEND URL survives a refresh: the replace clears static hosting, so
170
+ `--static` publishes a NEW host every run and the previous URL stops serving.
171
+ - Under `--keep-data`, which MERGES an env a deploy filled instead of replacing it, the static
172
+ URL survives too: rows kept, no re-seed, removed objects deleted. ⚠ Limits: a rename loses values,
173
+ a RETYPE reads unfit ones as null, env VALUES are not applied, a table trigger refuses it.
174
+ `--reset` replaces and re-seeds.
175
+ - `release create <name>` cuts a release from a running source and LANDS it in your workspace.
176
+ A release records that the source came up; it is the only thing `promote`/`tenant deploy` take.
177
+ - Refused: a taken name, and one that addresses a LOCATION instead of naming (`/`, `\`, `:`,
178
+ or a leading `.`). Every export derives its FILENAME from the name it is given, so
179
+ `release|ephemeral|workspace export` refuse those same shapes unless `--path` names the file.
180
+ - Carries EVERY table's SCHEMA either way; `--seed[=<guids>]` adds ROWS. Guids come from
181
+ `tables <backend>`; a redeploy KEEPS them.
186
182
  - `release transfer <name> --to-profile <profile>` copies a release to another
187
183
  workspace/instance by CONTENT (tar sha256): identical → reused; same name, other
188
184
  bytes → exit 2.
189
185
  - `promote <release>` / `tenant deploy <tenant> <release>` land it.
190
- `promote` adds a branch; ⚠ its TABLE edits hit live
191
- (`--allow-shared-schema-changes`). `tenant deploy` REPLACES: DROPS tables it lacks,
192
- CONVERTS retypes (`--seed`: rows).
193
- `promote` refuses a taken name/pinned slug (`SDK_IDENTITY_CONFLICT`), then
194
- EXITS NON-ZERO if a declared object did not arrive or a pinned slug is not served;
195
- `--set-live` waits on that (previous branch serving). Extra objects: reported;
196
- a check missing an input reports `unverified`, exit 0. `--json` on every release write:
197
- `completed` yes|no|unknown; UNKNOWN exits 9 — run `resolveWith`, never retry blind.
198
- `--expect-live <label>` (with `--set-live`) refuses if live moved; not atomic. Inspect a staged branch with
199
- `workspace export --branch <label>` or `workspace diff <entry> --branch <label>`.
200
- ⚠ The redis family, `s.lambda`, `s.db.direct_query`, `s.await`, `s.microservice.request`,
201
- `s.zip.*`, the raw-file readers, Datadog and Webflow need an INSTANCE CAPABILITY: they
202
- deploy clean and fail on the first request if the target lacks it. `export`/`deploy` list
203
- what the bundle needs — compare it to the target yourself.
186
+ - `promote` adds a branch; ⚠ its TABLE edits hit live (`--allow-shared-schema-changes`).
187
+ - `tenant deploy` REPLACES: DROPS tables it lacks, CONVERTS retypes (`--seed`: rows).
188
+ - `promote` refuses a taken name/pinned slug (`SDK_IDENTITY_CONFLICT`), then EXITS NON-ZERO
189
+ if a declared object did not arrive or a pinned slug is not served. `--set-live` switches
190
+ only after that check passes; a failure leaves the previous branch serving. Extra objects
191
+ are reported; a check missing an input reports `unverified`, exit 0.
192
+ - `--expect-live <label>` (with `--set-live`) refuses if live moved; not atomic.
193
+ - `--json` on every release write: `completed` yes|no|unknown; UNKNOWN exits 9 — run
194
+ `resolveWith`, never retry blind.
195
+ - Inspect a staged branch with `workspace export --branch <label>` or
196
+ `workspace diff <entry> --branch <label>`.
197
+ - ⚠ The redis family, `s.lambda`, `s.db.direct_query`, `s.await`, async runs,
198
+ `s.microservice.request`, `s.zip.*`, the raw-file readers, Datadog and Webflow need an
199
+ INSTANCE CAPABILITY: they deploy clean and fail on the first request if the target lacks it.
200
+ `export`/`deploy` list what the bundle needs — compare it to the target yourself.
204
201
  - Backend SECRETS stay out of the repo: declare the NAME, value empty, in `workspaceConfig({ env })`
205
202
  passed to `registerWorkspace()`; the VALUE lives in `xano/.env` — gitignored, kept across a
206
203
  pull, read by every build. `--backend-env-file <path>` replaces that default (CI has
@@ -233,9 +230,7 @@ and a `tenant:` only if throwaway (`standard`/`run` refused).
233
230
  - `workspace reset-tables <entry> --table <guid>` puts NAMED tables back to their
234
231
  compiled `table({ seed })` rows, touching no other table. Dry run unless `--write`.
235
232
  ⚠ ROWS BEFORE LOGIC: rows are workspace-shared like schema, so they reach production when
236
- applied even while the logic reading them is staged — no ordering makes a half-data change
237
- atomic. Reset rows FIRST, then `promote`: new rows under old logic break only a feature
238
- being removed; new logic over old rows breaks the one you are shipping.
233
+ applied, even while the logic reading them is staged. Reset rows FIRST, then `promote`.
239
234
  - `pull` refreshes THIS project from a backend: rewrites decoded files,
240
235
  keeps yours, lists and confirms (`--yes`).
241
236
  - `generate <source>`: the decoded tree ONLY, no project.
@@ -265,11 +260,9 @@ Non-obvious authoring rules:
265
260
  - **No callback builder.** Flat def-objects + `register*`, not
266
261
  `workspace(w => w.table(...))`. `workspace(name)` returns a named `new Xano()`;
267
262
  tables are `table({ schema: { col: f.text() } })`.
268
- - **Reference-helper picker:** `ref` = stack var (`as:` output), `inp` = input,
269
- `col` = table column (in `db.query` `where`), `auth("id")` = the caller,
270
- `c.*` = a constant. Pick by what you're pointing at.
271
- - **Foreign key is `f.tableRef(table)`, not `ref`.** `ref(name)` references a
272
- stack variable (a value); `f.tableRef` is the column constructor.
263
+ - **Foreign key is `f.tableRef(table)`, not `ref`.** `ref` = stack var (`as:` output),
264
+ `inp` = input, `col` = table column (in `db.query` `where`), `auth("id")` = the caller,
265
+ `c.*` = a constant; `f.tableRef` is the column constructor.
273
266
  - **Tagged values are DATA — a JS template literal cannot compose them.** `${ref(...)}`
274
267
  (or `"a" + ref(...)`) stringifies the tag object at BUILD time: ``c.text(`Hi ${ref("u.name")}`)``
275
268
  type-checks and encodes the literal text `Hi [object Object]`, served verbatim.
@@ -283,11 +276,11 @@ Non-obvious authoring rules:
283
276
  - **`get_input`/`get_raw_input` read the whole payload**, not one named input
284
277
  (args are `{ as?, encoding?, excludeMiddleware? }` — no `name`). For a single
285
278
  input use `inp("name")`.
286
- - **To match every row, omit `where` — never pass a constant.** `where: c.bool(true)` is
287
- not "no filter": a bare scalar literal states no condition and the engine reads the
288
- resulting `context.search` as garbage, so it throws. An absent `where` is how "every
289
- row" is spelled. A raw `Value` `where` stays the escape hatch for a clause built
290
- elsewhere — `inp("clause")`, `ref("built_where")`, or `c.text("id > 0")`.
279
+ - **A `where` is a comparison, never a value.** To match every row, omit `where`. A value
280
+ `where` — `c.bool(true)`, a text clause, or one built at run time (`inp("clause")`,
281
+ `ref("built_where")`) — throws at build: the engine reads a filter only as a comparison
282
+ tree and runs anything else over EVERY row. Bind run-time values as operands instead:
283
+ `expr(col("status"), "=", inp("status"))`.
291
284
 
292
285
  ### Tables and columns
293
286
 
@@ -305,8 +298,7 @@ Non-obvious authoring rules:
305
298
  defaults or a 400. HTTP binds it fine. `--strict` fails on it.
306
299
  - **Numeric columns lose money quietly.** A normalized table's `f.decimal` reads
307
300
  `0.12345678` back as `0.12346`; `f.int` saturates at `9223372036854775807`
308
- instead of failing. Both at HTTP 200 and plausible on read, so it surfaces as
309
- arithmetic that stops reconciling. Hold money as a count of the smallest unit;
301
+ instead of failing, both at HTTP 200. Hold money as a count of the smallest unit;
310
302
  exact bounds: `llms/fields.md`.
311
303
  - **Self-referencing tables** need the bare-name form: inside `tweets`'s own
312
304
  schema, write `f.tableRef("tweets", { type: "int" })` — the `const tweets`
@@ -333,22 +325,17 @@ Non-obvious authoring rules:
333
325
  ### Reading and writing rows
334
326
 
335
327
  - **DB reads are field-match, not `where`-expr.** `db.get`/`db.edit`/`db.del`/
336
- `db.has`/`db.patch` match one field: `{ fieldName, fieldValue }` (`fieldName`
337
- defaults to the PK `id`). Only `db.query` takes a `where`/`additionalWhere`
338
- `expr(...)`; writes (`db.add`/`db.edit`/`db.add_or_edit`) take a `row`/`data`.
339
- Signatures: `llms/statements-data.md`.
340
- - **Single-field only — no composite match.** These ops match exactly ONE field;
341
- there is no two-field form (the engine's by-field lookup takes a single
342
- predicate). For a `(a, b)` existence/fetch — e.g. dedupe a `(habit, date)`
343
- check-in — use `db.query({ where: [expr(col("habit"), "=", ...), expr(col("date"), "=", ...)], as })`
344
- (a `where` array is ANDed) and branch on the result, rather than pushing the
345
- check to the client.
328
+ `db.has`/`db.patch` match exactly ONE field: `{ fieldName, fieldValue }` (`fieldName`
329
+ defaults to the PK `id`); there is no composite match. Only `db.query` takes a
330
+ `where`/`additionalWhere` `expr(...)`; writes (`db.add`/`db.edit`/`db.add_or_edit`) take a
331
+ `row`/`data`. For an `(a, b)` existence/fetch (e.g. dedupe a `(habit, date)` check-in), use
332
+ `db.query({ where: [expr(col("habit"), "=", ...), expr(col("date"), "=", ...)], as })`
333
+ (a `where` array is ANDed) and branch on the result. Signatures: `llms/statements-data.md`.
346
334
  - **Drilling into a maybe-null `db.get` result 500s — use `ref(path, { safe: true })`.**
347
335
  `db.get` binds `null` on a no-match, but a nested `ref("owner.user_id")` raises a runtime
348
336
  "Unable to locate var" (HTTP 500) when `owner` is null — an ownership guard throws instead
349
- of failing cleanly. Two correct shapes:
350
- - Guard existence first — `s.precondition({ expr: expr(ref("owner"), "!=", c.null()),
351
- error_type: "notfound", error: c.text("Not found.") })` — then drill WITHOUT `safe`.
337
+ of failing cleanly (same for a `single` `db.query`; warns `stack.drill-maybe-null`). Two correct shapes:
338
+ - Guard existence first — `guard.found("owner")` (a 404 precondition) — then drill WITHOUT `safe`.
352
339
  - Or drill null-safe inside an EXPRESSION or `obj()` operand:
353
340
  `expr(ref("owner.user_id", { safe: true }), "=", auth("id"))` yields `null` (the guard
354
341
  reads `false`) instead of 500ing. Works inside `obj({...})` too — no `s.set_var` hoist needed.
@@ -379,12 +366,12 @@ Non-obvious authoring rules:
379
366
  - **`s.api.call` / `s.task.call` / `s.trigger.call` / `s.workflow_test.call` are
380
367
  WORKFLOW-TEST ONLY.** Outside a `workflowTest({...})` stack the engine cannot reach
381
368
  the target, so one in a query/function/task deploys clean and then answers the first
382
- real request with `ERROR_FATAL: <Type> does not exist: <type>:<n>` — and not per
383
- host kind, the same call fails identically from a function a query runs.
369
+ real request with `ERROR_FATAL: <Type> does not exist: <type>:<n>`. The failure is not per
370
+ host kind: the same call inside a function that a query runs fails the same way.
384
371
  `export()` refuses them. `s.function.call`, `s.tool.call`, `s.middleware.call` and
385
- `s.addon.call` run anywhere, as does `s.function.run` (the ordinary function
386
- invocation). To share logic between endpoints, put it in a `defineFunction` and
387
- `s.function.run` it from both.
372
+ `s.addon.call` run anywhere, as does `s.function.run`. To share logic, put it in a
373
+ `defineFunction` and `s.function.run` it — NOT `s.function.call`, which binds a failing
374
+ target's error envelope instead of raising.
388
375
  - **`expect.*` is a unit-test assertion; `s.expect.*` is a workflow-test statement.**
389
376
  A statement's `mock` is keyed by TEST NAME; an undeclared name throws. See `llms/tests.md`.
390
377
  - **A helper returning `Statement[]` widens the stack and kills `InferResponse`.**
@@ -398,17 +385,15 @@ Non-obvious authoring rules:
398
385
  The regex filters (`regex_test`/`regex_match`/`regex_replace`/…) are PHP `preg_*`: the
399
386
  piped value is the PATTERN and must be delimiter-wrapped, and the ARGUMENT is the subject.
400
387
  Correct: `withFilters(c.regex(/^[a-z-]+$/i), fl.regex_test(inp("slug")))`.
401
- - A bare `c.text("^…$")` is an invalid pattern that matches *nothing* for every input,
402
- so a precondition on it silently rejects all values. `c.regex(body, "i")` wraps +
403
- escapes it for you (a JS `RegExp` too: `c.regex(/^…$/i)`).
404
- - Reversed — subject piped, pattern in the argument — reads correctly, type-checks, and
388
+ - A bare `c.text("^…$")` is an invalid pattern that matches *nothing* for every input, so
389
+ a precondition on it rejects all values. `c.regex(body, "i")` (or a JS `RegExp`) wraps + escapes it.
390
+ - Reversed (subject piped, pattern in the argument) type-checks and
405
391
  answers false for EVERY input, so an `if (matches) reject` guard admits what it refuses.
406
- - Build time refuses both: `withFilters` throws on a bare `c.text` pattern from ANY position
407
- in the chain (a normalizer in front of the regex filter is refused too; nothing upstream
408
- adds the delimiters) and on a pattern found in the subject slot; `s.expect.to_match` is the
409
- same PATTERN slot, refused both ways; a `ref`/`inp` pattern is passed through untouched.
410
- `export()` warns on a reversed pair in stored bytes.
411
- - Better still: a native typed input (`input.email`) over hand-rolled validation.
392
+ - `withFilters` throws on both: a bare `c.text` pattern at ANY position in the chain (a
393
+ normalizer in front does not add delimiters) and a pattern in the subject slot.
394
+ `s.expect.to_match` is the same PATTERN slot, refused both ways. A `ref`/`inp` pattern is
395
+ passed through untouched. `export()` warns on a reversed pair in stored bytes.
396
+ - Prefer a native typed input (`input.email`) over hand-rolled validation.
412
397
  - **An `auth()`-keyed limiter FAILS the request on any host with no caller identity —**
413
398
  **at every tier.** `s.redis.ratelimit({ key: withFilters(c.text("rl:"), fl.concat(auth("id"))), error: c.text("…") })`
414
399
  is the per-user form, and a public query, a task, or a function has no caller identity.
@@ -420,8 +405,8 @@ Non-obvious authoring rules:
420
405
  ### Identity, build, and deploy
421
406
 
422
407
  - **Same-name siblings collide — queries excepted: their identity carries group + verb.**
423
- Guids derive from `(type, name)`, so two functions (or tables, toolsets, …) sharing
424
- a name derive ONE guid and `export()` throws — give them DISTINCT names. A QUERY
408
+ Two functions (or tables, toolsets, …) sharing a name derive ONE guid and `export()`
409
+ throws — give them DISTINCT names. A QUERY
425
410
  derives from `(api group, verb, name)`, the engine's own uniqueness: `GET items` +
426
411
  `POST items`, and `items` across two groups, coexist, and the lock keys the same
427
412
  composed identity (`query:blog|GET|items`) — changing a query's verb or group
@@ -455,29 +440,27 @@ Non-obvious authoring rules:
455
440
  the runner has. An explicit `--profile` against it is a hard error too, not a displacement.
456
441
  - On disk: `npx @xano/sdk profile add <name> --instance … --workspace-id <n>` reads the token
457
442
  from piped stdin, else PROMPTS (a flag would reach the process list); the instance must accept it.
458
- `auth.json` holds a map of named profiles, selected by `--profile <name>`. The older
459
- `$XANO_REFRESH_TOKEN` + `$XANO_CLIENT_ID` pair still works but ROTATES: single-use.
460
- - **Event-driven objects fire on an EPHEMERAL.** A `task` (scheduled), an `mcpServer`,
461
- and every trigger — `tableTrigger` included — run normally on an ephemeral env, which
462
- is where `deploy` sends them. So test an event-driven design (screen-on-insert, cron
463
- cleanup, MCP tool call) by deploying it and letting it run.
443
+ `auth.json` holds a map of named profiles, selected by `--profile <name>`.
444
+ `$XANO_REFRESH_TOKEN` + `$XANO_CLIENT_ID` also authenticate, but the refresh token is single-use (it ROTATES).
445
+ - **Event-driven objects run once deployed.** A `task` (scheduled), an `mcpServer`, and
446
+ every trigger — `tableTrigger` included — run on every deploy target, the Xano Engine and
447
+ an ephemeral alike. Test an event-driven design (screen-on-insert, scheduled cleanup, MCP
448
+ tool call) by deploying it and letting it run.
464
449
 
465
450
  ## Statements
466
451
 
467
452
  Reachable through the `s` namespace: `s.<path>({...})`. Declarative statements
468
453
  take one typed args object (field names match the engine); every surface's field
469
454
  signature is in `llms/statements-catalog.md`. Specials (`[special]`) are
470
- hand-authored: control flow is below, and the rest are in the `llms/statements-*`
471
- topic files this doc's navigation names.
472
- Wrap an `input`-routed `value` field in `ignored(...)` to store it but SKIP it at
473
- runtime — the engine records `<name>:ignore` and the parameter falls back to its
474
- default. Not the same as an empty value, and not the same as omitting the field
475
- (which stores no entry at all). Mostly seen on a pulled workspace. A field written
476
- into `context` instead (the `s.math.*`/`s.text.append` mutation family) has no slot
477
- for the flag and THROWS rather than dropping it.
455
+ hand-authored: control flow is below, the rest are in the `llms/statements-*` topic files.
478
456
  Fields marked `value` take a `Value` (`c.*`/`ref`/`inp`); `comparison` takes an
479
457
  `expr(...)`. A `→ as: <type>` suffix names what the statement's `as:` output var
480
458
  holds (curated, not exhaustive — absence means read the `[output]` flag and prose).
459
+ `ignored(...)` around an `input`-routed `value` field stores it but SKIPS it at runtime: the
460
+ engine records `<name>:ignore` and the parameter takes its default. Distinct from an empty
461
+ value and from omitting the field (no entry stored). Mostly seen on a pulled workspace. On a
462
+ `context`-routed field (the `s.math.*`/`s.text.append` mutation family) `ignored(...)` THROWS:
463
+ there is no slot for the flag.
481
464
 
482
465
  ### Specials — authored signatures
483
466
 
@@ -500,23 +483,21 @@ Control flow & blocks (each nests a sub-stack; block specials name it `body`):
500
483
 
501
484
  > Read when deciding WHAT to build — every authorable primitive, what each is, and which factory + register method builds it. Also when `register*` will not typecheck an array built by `.flatMap()`/`.concat()`.
502
485
 
503
- Author with the factory, register on the Xano instance, lands under the payload key. Each line ends with a one-liner on what the primitive is.
504
-
505
486
  ### Choosing a kind
506
487
 
507
- Choose by who or what starts the work. Each rule names the kind that fits and the one it gets mistaken for.
488
+ Choose by who or what starts the work.
508
489
 
509
490
  - **Logic other code calls** → `defineFunction`, run with `s.function.run`. A `query` is the only kind an HTTP client reaches by verb + path; a `tool` is what an `agent()` or an MCP client calls. Logic serving two callers (an endpoint AND a tool) lives in one function both call.
510
- - **Work on a timer** → `task` (cron or interval). **Work a request starts but does not wait for** → `s.function.run({ fn, runtime: { mode: "async-shared" } })`, which binds a job id, not the result (collect with `s.await`). **Work that follows a row change** → `tableTrigger`: it fires on every insert/update/delete of the table, whichever stack writes it, so the same side effect placed in one endpoint's stack misses every other write path.
511
- - **The same steps before or after many objects** (an auth check, a rate limit, logging) → `middleware`, attached per host (`middleware: { pre, post }` on a query, function, task, tool or API group) or to every host of a kind with `workspaceConfig({ middleware: { query, function, task, tool } })` — not a function call repeated at the top of each stack.
491
+ - **Work on a timer** → `task` (fixed interval, no cron). **Work a request starts but does not wait for** → `s.function.run({ fn, runtime: { mode: "async-shared" } })`, which binds a job id, not the result (collect with `s.await`). **Work that follows a row change** → `tableTrigger`: it fires on every write to the table, whichever stack writes it (except a trigger's own), so the same side effect in one endpoint's stack misses every other write path. It runs after commit, async — validation belongs in the writing stack (`llms/triggers.md`).
492
+ - **The same steps before or after many objects** (an auth check, a rate limit, logging) → `middleware`, attached per host (`middleware: { pre, post }` on a query, function, task, tool, API group, prompt, resource, or realtime server/channel/message) or to every host of a kind with `workspaceConfig({ middleware: { query, function, task, tool } })` — not a function call repeated at the top of each stack.
512
493
  - **Related rows on returned rows** → an `addon` attached to the read through its `addon: [{ addon, as, input }]` option (`db.query`/`get`/`add`/`edit`/`patch`), merged onto each row under `as` and typed in `InferResponse` — not a second read plus a loop that stitches rows together.
513
- - **AI.** An LLM running inside the backend → `agent()`, started from a stack with `s.ai.agent.run`; it has no public endpoint. An external AI client (Claude, Cursor, any MCP client) calling the backend → `mcpServer()`. Standing instructions for Xano's own builder AI → `knowledge()` (a local coding agent reads the same files in the repo); an `agent()` run never reads it. The actions either one calls → `tool()`. What an MCP server serves besides tools (`prompt()`, `resource()`) and when each fits: `llms/kinds-agent-mcp.md`.
494
+ - **AI.** An LLM running inside the backend → `agent()`, started from a stack with `s.ai.agent.run`; it has no public endpoint. An external AI client (Claude, Cursor, any MCP client) calling the backend → `mcpServer()`. Standing instructions for Xano's own builder AI → `knowledge()` (who reads it: `llms/kinds-knowledge.md`). The actions either one calls → `tool()`. What an MCP server serves besides tools (`prompt()`, `resource()`) and when each fits: `llms/kinds-agent-mcp.md`.
514
495
  - **Pushing to connected clients** → `realtimeServer` → `realtimeChannel` → `realtimeMessage` (the handler for a frame a client sends — the realtime analogue of a query). A server-side push from any stack is `s.realtime.publish`; a client polling a `query` is the substitute this replaces.
515
496
  - **Code the typed surface cannot express** → a lambda (`s.lambda`, `fl.lambda`) for a short JavaScript body, LAST, after native filters and expressions (`llms/lambda.md`); a `microservice` for a long-running container or another language; `s.api.request` for a service that already has an HTTP API.
516
497
  - **Tests** → `tests` on a `query`/`defineFunction`/`middleware` for that one object's input → output; a `workflowTest` for a flow across objects (`s.function.call`, `s.api.call`, `s.task.call`) asserted with `s.expect.*`.
517
498
  - **Reacting to the platform** → `errorTrigger` (an error signature first seen, regressing, or marked fixed) and `workspaceTrigger` (branch new/merge/live). What one connection to an MCP server, agent, realtime server or channel may see or do → that object's connection trigger.
518
499
 
519
- ⚠ Composing a workspace from independently-authored modules: `register*` takes its defs however they arrive, but `modules.flatMap((m) => m.tables)` does NOT typecheck. `Array.prototype.flatMap` binds its element type to the FIRST element, so every later module's tables are checked against that one table's schema — the error compares two unrelated column names and mentions neither `flatMap` nor the cause. `.concat()` collapses the same way. Two spellings work: pass an array LITERAL (`registerTables([...a.tables, ...b.tables])` — spreads are fine, TypeScript infers the union across every element at once), or annotate the module array with the wide aliases `AnyTableDef` / `AnyQueryDef` / `AnyFunctionDef` / `AnyAddonDef`, exported for exactly the four def types whose generics can collapse this way. Widening the array costs nothing: the typing you need lives on the `table()`/`query()` handle you hold and pass to `s.db.*`, and is never read back off the registered array.
500
+ Composing a workspace from modules: `registerTables(modules.flatMap((m) => m.tables))` does NOT typecheck — `flatMap` (and `.concat()`) binds its element type to the FIRST element, so later tables are checked against that one table's schema; the error names two unrelated columns, not the cause. Pass an array LITERAL (`registerTables([...a.tables, ...b.tables])`), or annotate the module array with the wide aliases `AnyTableDef` / `AnyQueryDef` / `AnyFunctionDef` / `AnyAddonDef`. Widening loses nothing: typing lives on the `table()`/`query()` handle passed to `s.db.*`.
520
501
 
521
502
  - function: `defineFunction` → `Xano.registerFunctions` → payload `function` — Reusable server-side logic (a custom function) callable from any stack via `s.function.run`.
522
503
  - table: `table` → `Xano.registerTables` → payload `dbo` — A database table: typed columns (`f.*`), indexes, and views; the schema other kinds read and write.
@@ -534,15 +515,15 @@ Choose by who or what starts the work. Each rule names the kind that fits and th
534
515
  - resource: `resource` → `Xano.registerResources` → payload `resource` — An MCP resource: contents an MCP client reads by URI (a literal or a `{variable}` template), produced by a stack. Exposed by an `mcpServer`.
535
516
  - mcp_server: `mcpServer` → `Xano.registerMcpServers` → payload `toolset` — An MCP server exposing tools, prompts and resources to external MCP clients.
536
517
  - agent: `agent` → `Xano.registerAgents` → payload `toolset` — An AI agent: an LLM configuration plus the tools it can call. Invoke it from any stack (query/function/task/tool/trigger) with `s.ai.agent.run` — no public endpoint; the result is a rich envelope whose completion text is at `.result`.
537
- - task: `task` → `Xano.registerTasks` → payload `task` — A scheduled background job (cron/interval) that runs a stack on a timer.
538
- - workflow_test: `workflowTest` → `Xano.registerWorkflowTests` → payload `workflow_test` — An end-to-end test: a named stack with NO input and NO response that invokes other objects (`s.function.call`, `s.task.call`, `s.api.call`) and asserts on what they bind with `s.expect.*`. `datasource` defaults to `""` (an EMPTY datasource, recommended); naming one CLONES it before every run — see `llms/kinds-core.md`.
539
- - middleware: `middleware` → `Xano.registerMiddleware` → payload `middleware` — A reusable pre/post stack attached to a query/function/task/tool/API group to run before or after its own logic.
518
+ - task: `task` → `Xano.registerTasks` → payload `task` — A scheduled background job that runs a stack on a fixed interval (no cron).
519
+ - workflow_test: `workflowTest` → `Xano.registerWorkflowTests` → payload `workflow_test` — An end-to-end test: a named stack with NO input and NO response that invokes other objects (`s.function.call`, `s.task.call`, `s.api.call`) and asserts on what they bind with `s.expect.*`. `datasource`: `llms/kinds-core.md`.
520
+ - middleware: `middleware` → `Xano.registerMiddleware` → payload `middleware` — A reusable pre/post stack attached to a host (query, function, task, tool, API group, prompt, resource, realtime server/channel/message) to run before or after its own logic.
540
521
  - addon: `addon` → `Xano.registerAddons` → payload `addon` — A reusable read fragment that enriches a query result by joining related table data.
541
522
  - realtime_server: `realtimeServer` → `Xano.registerRealtimeServers` → payload `realtime_server` — A realtime (websocket) server: the canonical-addressed container that owns realtime channels. Off until `enabled: true`. Returns a handle with `getUrl(baseUrl)`/`getPath()` for the client's socket URL (`wss://<host>/ws/<canonical>`).
542
523
  - channel: `realtimeChannel` → `Xano.registerRealtimeChannels` → payload `channel` — A realtime channel: a joinable path on a realtime server (`rooms/{room_id}`) with typed path params, join/publish policy, a client-visible conversation transcript, and delivery semantics. Owns message handlers. Returns a handle with `getChannel(params)` for the path a client joins.
543
524
  - message: `realtimeMessage` → `Xano.registerRealtimeMessages` → payload `message` — A realtime message handler: a named message type on a channel with its own typed payload and stack — the realtime analogue of a query. Pass the `realtimeChannel()` handle as `channel` and the owning server comes with it.
544
525
  - microservice: `microservice` → `Xano.registerMicroservices` → payload `microservice` — A container workload deployed alongside the workspace, called from a stack with `s.microservice.request`. Def shapes (`builtin` containers vs a `helm` chart) and the SECRET-handling rules its config carries: `llms/statements-calls.md`.
545
- - knowledge: `knowledge` → `Xano.registerKnowledge` → payload `knowledge` — Markdown shared by every AI that builds the backend — Xano's own AI (the builder agent, Meta API / MCP readers) and a local coding agent reading the same files — never an `agent()` run: an `agents.md` of standing instructions, a `skill`, or a `doc`. The body is a real markdown FILE via `knowledgeFile("./x.md", import.meta.url)`, and `mode` decides how much of it reaches the agent.
526
+ - knowledge: `knowledge` → `Xano.registerKnowledge` → payload `knowledge` — Markdown for the AIs that build the backend (never an `agent()` run): an `agents.md` of standing instructions, a `skill`, or a `doc`. The body is a markdown FILE via `knowledgeFile("./x.md", import.meta.url)`; readers and `mode`: `llms/kinds-knowledge.md`.
546
527
  - workspace: `workspaceConfig` → `Xano.registerWorkspace` → payload `workspace` — Workspace-level configuration such as default middleware chains and request-history defaults per host kind.
547
528
 
548
529
  # Core def shapes
@@ -557,36 +538,40 @@ to survive a rename).
557
538
 
558
539
  - `defineFunction({ name, guid?, description?, docs?, workspace?, input?, stack?, response?, tests? })`
559
540
  - `query({ name, verb, apiGroup?, guid?, auth?, input?, stack?, response?, responseType?, apiEnabled?, disabled?, cache?, description?, docs?, tests?, example? })` — a `cache` setting turns caching on unless `active: false`
560
- - `verb`: `"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD"` (required), UPPERCASE. Anything else — most often a lowercase `"post"` — makes `query()` THROW, because Xano does NOT reject it: it stores the verb as NULL, a null verb serves as GET, and the endpoint then answers on the wrong method while the one you meant 404s `Unable to locate request.`
541
+ - `verb`: `"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD"` (required), UPPERCASE. Anything else (e.g. lowercase `"post"`) makes `query()` THROW — Xano would store NULL, a null verb serves as GET, and the verb you meant 404s `Unable to locate request.`
561
542
  - `apiGroup`: an `apiGroup()` def handle (or its name) — binds by guid, stable across syncs. Raw numeric `apiGroupId?` is the escape hatch and wins if both given.
562
- - `auth`: `false` (no auth) or an auth-table id; `responseType`: `"standard" | "stream"` (default `standard`) — any other spelling THROWS, since Xano stores an unrecognized one as NULL and a null buffers as `standard`, so a misspelled stream quietly does not stream.
543
+ - `auth`: `false` (no auth) or an auth-table id; `responseType`: `"standard" | "stream"` (default `standard`) — any other spelling THROWS (Xano would store NULL and buffer it as `standard`). ⚠ `s.api.stream` does nothing unless `responseType: "stream"`: in a `standard` query its chunk is SILENTLY DROPPED (no warning) and the normal `response` is served. Paired, each `s.api.stream({ value })` call emits ONE Server-Sent Event — the wire is `Content-Type: text/event-stream`, a `data: <json of value>` line per event, with an `id:` line that is a MILLISECOND TIMESTAMP and is NOT unique (ids repeat within a ms, so `Last-Event-ID` resume is unreliable). The query's own `response` is not sent in `stream` mode. Consumer recipe (`EventSource`/`fetch`): `llms/client.md`.
563
544
  - `name` is the endpoint PATH within the group.
564
545
  - A `{param}` segment is a URL PATH PARAM bound to the input of the same name, and segments chain: `name: "blog/{slug}/review/{review_id}"` + `input: { slug: input.text(), review_id: input.int() }`. Read it with `inp("slug")` like any other input.
565
- - Every `{param}` MUST have a matching input or `query()` THROWS — Xano treats an unbound marker as inert route text, so the endpoint would answer on the path and see nothing.
566
- - A `{param}` need NOT be a whole segment (`"blog/post-{slug}"` routes fine), but its type must fit one segment (no object/list/json/file/geo/vector); there are no wildcards or patterns. `required: true` is NOT demanded (the engine's editor leaves path inputs unmarked).
546
+ - Every `{param}` MUST have a matching input or `query()` THROWS — Xano would treat an unbound marker as literal route text.
547
+ - A `{param}` need NOT be a whole segment (`"blog/post-{slug}"` routes fine), but its type must fit one segment (no object/list/json/file/geo/vector); there are no wildcards or patterns. `required: true` is NOT demanded.
567
548
  - An input a `GET`/`DELETE`/`HEAD` looks ONE ROW up by (`s.db.get`/by-field edit/patch/delete; not `has` or an email/token/code) belongs in the path — `export()` warns `query.path-segment-candidate`: `getPath()` types STATIC. A segment is any value naming WHICH resource is wanted (`"shop/{country}"`); one that NARROWS A LIST (`s.db.query`) stays a query param. Intended? `diagnostics: { allow: [code] }` on the query (any def, for its own advisories) accepts it under `--strict`.
568
549
  - Routes are matched FIRST-FIT in creation order, and a literal gets NO precedence over a `{param}`: `"runs/{id}"` (a text `id`) created before `"runs/trend"` answers `GET /runs/trend` itself. Two routes in one group and verb that one request path can match are REFUSED at `export()` (`query.route-shadowed`) — reordering `registerQueries` cannot fix it, since a release keeps an existing route first. Make the paths disjoint (`"runs/by-id/{id}"`), or declare a numeric param `input.int({ required: true })` (or `decimal`): only a REQUIRED int/decimal segment matches digits only — an OPTIONAL one matches any text, so `input.int()` still takes `trend`.
569
550
  - Inputs absent from the path are ordinary query-string/body params.
570
- - Name charset is ONLY `A-Za-z0-9_-/{}`, max 200: a `.` (`"export.zip"`) is NOT rejected by Xano — it stores an EMPTY name that deploys clean then 404s forever, so `query()` THROWS. Use `"export_zip"` and set the extension in the response headers.
551
+ - Name charset is ONLY `A-Za-z0-9_-/{}`, max 200: a `.` (`"export.zip"`) THROWS — Xano would store an EMPTY name that deploys clean then 404s. Use `"export_zip"` and set the extension in the response headers.
571
552
  - **Client recipe:** `q.getPath({ params: { slug: "hello" } })` → `/api:<canonical>/blog/hello` — never interpolate by hand.
572
553
  - `getPath` percent-encodes each value (so `?`/`#`/spaces stay in their segment) and throws on what encoding cannot contain: a `/`, and a segment that becomes `.`/`..` as sent (a URL parser drops those before routing, addressing a different endpoint).
573
554
  - The keys are typed from the literal `name`, so a typo is a compile error.
574
555
  - `q.toSearchParams(input)` drops GET path params (free `query.toSearchParams` keeps them); lists send `k[]=a&k[]=b` (`k=a&k=b` binds only `b`).
575
556
  - Browser bundle cost, the `routes.gen.ts` alternative (paths and request types), and spot-checking a def from Node: `llms/client.md`.
576
557
  - `apiGroup({ name, guid?, canonical?, description?, docs?, swagger?, apiGroupEnabled?, documentation?, cors?, middleware? })` — a query container; queries bind to it via their `apiGroup`. `canonical` holds only letters, digits, `_` and `-` (it is the `<canonical>` of `/api:<canonical>`); anything else THROWS at build.
577
- - `documentation?`: `{ require_token? }` — the gate on this group's hosted docs. `require_token: true` IS the declaration; the token lives in `xano/.secrets.json` under this group's guid, and a literal `token` FAILS the export. ⚠ ALWAYS emitted, present or not: an absent key is written as the engine default on import, so omitting the block CLEARS an existing gate (the opposite of the `workspaceConfig` rule). `swagger: true` publishes the docs; `require_token` gates them only alongside a non-empty token, so `swagger: true` with no gate makes the whole group readable by anyone with the URL — export warns once per build and `--strict` fails; `diagnostics: { allow: ["api-group.docs-public"] }` accepts it. A declared gate with NO token drops the block, so those bytes clear it: export FAILS under `swagger: true`, and with `swagger` off warns and completes.
558
+ - `documentation?`: `{ require_token? }` — the gate on this group's hosted docs; `swagger: true` publishes the docs. `require_token: true` IS the declaration; the token lives in `xano/.secrets.json` under this group's guid.
559
+ - The block is ALWAYS emitted: an absent key is written as the engine default on import, so omitting it CLEARS an existing gate (the opposite of the `workspaceConfig` rule).
560
+ - ⚠ `require_token` gates them only alongside a non-empty token: `swagger: true` with no gate makes the whole group readable by anyone with the URL — export warns once per build and `--strict` fails; `diagnostics: { allow: ["api-group.docs-public"] }` accepts it.
561
+ - A declared gate with NO token drops the block, clearing the gate: export FAILS under `swagger: true`, and with `swagger` off warns and completes.
562
+ - A literal `token` FAILS the export.
578
563
  - `cors?`: `{ mode?, allowOrigins?: string[], allowHeaders?: string[], allowCredentials?, maxAge?, allowMethods?: { get?, post?, put?, patch?, delete?, head? } }`.
579
- - `mode?`: `"default"` (the default) | `"custom"` | `"disabled"`, lowercase — a fourth value THROWS at export (`apiGroup()` itself does not check), because Xano neither rejects nor blanks it: it DROPS THE WHOLE API GROUP on import, so the deploy succeeds and every query in the group 404s. ⚠ Every OTHER field applies only under `"custom"`: `"default"` serves a FIXED permissive policy (any origin, `allow-headers: *`, `allow-credentials: true`, `max-age: 86400`) and ignores the block, so setting `maxAge`/`allowCredentials`/`allowHeaders` alone changes nothing. `"disabled"` sends no CORS headers at all, so every browser call fails.
564
+ - `mode?`: `"default"` (the default) | `"custom"` | `"disabled"`, lowercase — a fourth value THROWS at export (`apiGroup()` itself does not check); otherwise Xano DROPS THE WHOLE API GROUP on import (deploy succeeds, every query 404s). ⚠ Every OTHER field applies only under `"custom"`: `"default"` serves a FIXED permissive policy (any origin, `allow-headers: *`, `allow-credentials: true`, `max-age: 86400`) and ignores the block, so setting `maxAge`/`allowCredentials`/`allowHeaders` alone changes nothing. `"disabled"` sends no CORS headers at all, so every browser call fails.
580
565
  - ⚠ Under `"custom"`, `allowOrigins` is matched as EXACT strings (scheme+host+port, no wildcard or subdomain expansion) and `"*"` is compared as a literal origin — it matches NOTHING. An unmatched origin gets no `access-control-*` headers at all, so the browser call fails while export, deploy and the preflight look fine. Name each origin, or use `mode: "default"` for any-origin. `allowMethods` gates the REAL response too: a verb left off gets no CORS headers back even though its preflight passes. Export warns on an empty origin list, a `"*"` entry, and a policy with no method enabled; a non-origin entry (trailing `/`, path) is refused.
581
566
  - Tasks, workflow tests, middleware and tools below (agents and MCP servers: `llms/kinds-agent-mcp.md`) share the envelope conventions (`guid?`, `description?`, `docs?`, `tags?`, `history?`) unless noted.
582
567
  - `task({ name, guid?, description?, docs?, datasource?, active?, tags?, history?, schedule?, stack?, middleware? })` — a scheduled background job (function-like `stack`, no `input`/`response`). `active?` defaults `true`; `active: false` deploys it parked.
583
- - `schedule?`: a `ScheduleDef[]` (NOT a single object) — `{ startsOn, freq?, repeatEnabled?, endsOn?, endsEnabled? }`. `startsOn`/`endsOn` are **timestamp strings** validated at encode time — `"2026-01-01T00:00:00Z"`, or the space-separated `"2026-01-01 00:00:00+0000"` a pulled workspace carries — never epoch numbers, and never zoneless; `freq` is the repeat interval **in SECONDS** (omitted ⇒ runs ONCE) — spell it `every("15m")`, a compile-time duration-to-seconds helper (`s`/`m`/`h`/`d`/`w`, terms concatenate). No cron, no timezone — a fixed-offset `startsOn` drifts an hour at each DST change; for a local time run hourly, gated on the local hour `withFilters(c.now(), fl.epochms_date("G", "America/New_York"))`. `repeatEnabled?`/`endsEnabled?` follow whether `freq`/`endsOn` is set and are recovery-only — state one to reproduce a stored gate left OFF. Fires on an ephemeral (see Gotchas).
584
- - `workflowTest({ name, guid?, description?, docs?, datasource?, active?, tags?, stack? })` — an end-to-end test. NO `input`/`response`: `.call` something with an `as`, then assert on that var — `s.function.call({ fn, input, as: "r" })`, `s.expect.to_equal({ expr: ref("r"), value: c.int(42) })`. `s.expect.*` belongs here — it is not inert elsewhere (a failure 500s the request), so treat one in a query/function/task as a mistake to remove. `active?` defaults `true`; chain tests with `s.workflow_test.call({ workflowTest: <def handle> })`.
585
- - `datasource?`: Default `""` is an EMPTY datasource (recommended), not "no datasource". Any non-empty name makes the engine CLONE it before EVERY run — against production-sized data, slow enough to fail the run, which is why `"live"` warns at compile time. On an EPHEMERAL, `"live"` holds only the seed fixtures (plus rows a `--keep-data` deploy kept), so it is the way to read `table({ seed })` rows — a small clone, dropped after the run. ⚠ The value is STORED, so clear it before you promote or the same test clones the real database.
568
+ - `schedule?`: a `ScheduleDef[]` (NOT a single object) — `{ startsOn, freq?, repeatEnabled?, endsOn?, endsEnabled? }`. `startsOn`/`endsOn` are **timestamp strings** validated at encode time — `"2026-01-01T00:00:00Z"`, or the space-separated `"2026-01-01 00:00:00+0000"` a pulled workspace carries — never epoch numbers, and never zoneless; `freq` is the repeat interval **in SECONDS** (omitted ⇒ runs ONCE) — spell it `every("15m")`, a compile-time duration-to-seconds helper (`s`/`m`/`h`/`d`/`w`, terms concatenate). No cron, no timezone — a fixed-offset `startsOn` drifts an hour at each DST change; for a local time run hourly, gated on the local hour `withFilters(c.now(), fl.epochms_date("G", "America/New_York"))`. `repeatEnabled?`/`endsEnabled?` follow whether `freq`/`endsOn` is set and are recovery-only — state one to reproduce a stored gate left OFF. Runs on every deploy target (`llms.txt` Gotchas).
569
+ - `workflowTest({ name, guid?, description?, docs?, datasource?, active?, tags?, stack? })` — an end-to-end test. NO `input`/`response`: `.call` something with an `as`, then assert on that var — `s.function.call({ fn, input, as: "r" })`, `s.expect.to_equal({ expr: ref("r"), value: c.int(42) })`. `s.expect.*` belongs here — it is not inert elsewhere (a failure 500s the request), so treat one in a query/function/task as a mistake to remove. `active?` defaults `true`; `active: false` parks the test — `test run-all`/`deploy --test` SKIP it (reported `status: "skipped"`, never failing the suite), `test list` shows it `inactive`, and `test run "<name>"` still runs it. Chain tests with `s.workflow_test.call({ workflowTest: <def handle>, as: "child" })` then `s.expect.to_be_null({ expr: ref("child") })`, or a failing child passes the parent.
570
+ - `datasource?`: Default `""` is an EMPTY datasource (recommended), not "no datasource". Any non-empty name is CLONED before EVERY run — against production-sized data, slow enough to fail the run; `"live"` warns at compile time. On an EPHEMERAL, `"live"` holds only the seed fixtures (plus rows a `--keep-data` deploy kept): the way to read `table({ seed })` rows — a small clone, dropped after the run. ⚠ The value is STORED, so clear it before you promote or the same test clones the real database.
586
571
  - `middleware({ name, guid?, description?, docs?, resultStrategy?, exceptionPolicy?, tags?, history?, input?, stack?, response?, responseShape?, tests? })` — a pre/post interceptor (function-like `stack`); attach it via a host's `middleware: { pre, post }`. ⚠ `input` ENCODES but an ATTACHED middleware never has it bound — the host request binds its own inputs, so `inp()` inside pre/post fails at runtime with `Unable to locate input` and a declared default does not stand in (`export()` warns). Read the request body with `s.util.get_all_input` instead; it yields a `{ type, vars }` envelope whose `vars` DIFFERS BY PHASE: `pre` → the request inputs (`payload.vars.<field>`); `post` → `{ status, result }`, the host's outcome (`payload.vars.result.<field>`; plus `payload` on an error). A request field read in `post` 500s after the host already ran (`export()` warns); read the request there with `s.util.get_raw_input`. `s.middleware.call` is the one path that DOES bind the declared map.
587
- - `resultStrategy?`: `"merge" | "replace"` (default `merge`) — how the middleware `response` folds into the accumulator of the phase it is ATTACHED to, and the two phases accumulate DIFFERENT things. In `post` the accumulator is the host's RESULT, so a returned object changes what the CALLER receives. In `pre` it is the host's REQUEST INPUTS, so a returned object changes what the HOST receives. `merge` folds key-by-key, `replace` substitutes wholesale; either way the next entry in the chain sees the updated value. So `pre` + `replace` DISCARDS every caller input the middleware does not re-emit, and a discarded input is then unreadable — a 500, even where it is declared `required: false`, because input defaulting has already happened by the time the override lands.
588
- - `exceptionPolicy?`: `"silent" | "rethrow" | "critical"` (default `"rethrow"` — a throw ABORTS the request and surfaces the authored error/status, which is what a guard wants). `"silent"` swallows the throw and lets the request through, so a guard set to it is NOT enforced — use it only for advisory middleware. `"critical"` is `"rethrow"` plus skipping the `post` chain.
589
- - `tool({ name, guid?, description?, instructions?, docs?, enabled?, title?, annotations?, icons?, output?, tags?, history?, input?, stack?, response?, responseShape?, middleware? })` — a function-like operation (`input`/`stack`/`response`) that a toolset (MCP server or agent) exposes. Register it, then reference it from a toolset's `tools`. `title`/`annotations`/`icons`/`output` are MCP metadata (`llms/kinds-agent-mcp.md`).
572
+ - `resultStrategy?`: `"merge" | "replace"` (default `merge`) — how the middleware `response` folds into its phase's accumulator: in `post` the host's RESULT (changes what the CALLER receives), in `pre` the host's REQUEST INPUTS (changes what the HOST receives). `merge` folds key-by-key, `replace` substitutes wholesale; the next entry in the chain sees the updated value. `pre` + `replace` DISCARDS every caller input the middleware does not re-emit; reading a discarded input 500s, even one declared `required: false` (defaulting already ran).
573
+ - `exceptionPolicy?`: `"silent" | "rethrow" | "critical"` (default `"rethrow"` — a throw ABORTS the request and surfaces the authored error/status). `"silent"` swallows the throw and admits the request; never use it on a guard. `"critical"` is `"rethrow"` plus skipping the `post` chain.
574
+ - `tool({ name, guid?, description?, instructions?, docs?, enabled?, title?, annotations?, icons?, output?, tags?, history?, input?, stack?, response?, responseShape?, middleware? })` — a function-like operation (`input`/`stack`/`response`) that a toolset (MCP server or agent) exposes. Register it, then reference it from a toolset's `tools`. Name charset as a query's (`A-Za-z0-9_-/{}`, max 200). `instructions` is the description the MODEL/client sees (MCP `description`, agent-tool description) and what a connection trigger rewrites; it REPLACES `description`, which shows only when `instructions` is empty (both set warns `tool.description-shadowed`). `title`/`annotations`/`icons`/`output` are MCP metadata (`llms/kinds-agent-mcp.md`).
590
575
  - An addon is a single table-bound db query, NOT a statement stack: `addon({ name, table, tableAlias?, where?, sort?, output: [cols], cardinality?: "single"|"list"|"count"|"exists"|"aggregate", group?, eval?, input?, context? })`, registered via `registerAddons([...])`.
591
576
  - `table` auto-fills the `context.dbo` binding. ⚠ Never author `table: null` — that is a BROKEN table-less addon returning nothing; `codegen` emits it only for an already-broken pulled object.
592
577
  - `tableAlias` is its SQL alias (`context.dbo.as`), qualifying `where`/`sort` columns (`col("merchant.id")`).
@@ -614,7 +599,7 @@ response-bearing triggers) maps to the stored `result[]`:
614
599
  surface — `s.conditional`/`s.while` `when` (incl. each `elif` branch), and
615
600
  `db.query` `where`/`additionalWhere` (and the search triggers) — one shared tree.
616
601
 
617
- - `op`: `=`, `!=`, `>`, `<`, `>=`, `<=` (JS aliases `==` `===` `!==` are accepted and normalized).
602
+ - `op`: `=`/`==`/`!=` LOOSE (`null = 0` holds); `===`/`!==` STRICT; `>` `<` `>=` `<=`. Null check: `cond.isNull`.
618
603
  - `left`/`right` are `Value`s — `col("x")` (a table column, `db.*` statements only), `ref`, `inp`, `auth(...)`, or `c.*`.
619
604
  - For the full operator set (`in`/`like`/`ilike`/`between`/`contains`/`overlaps`/`@>`/`~`/`search`/…)
620
605
  use `cmp(left, op, right, { ignoreEmpty? })`; compose nested boolean logic with `and(...)`/`or(...)`.
@@ -628,7 +613,7 @@ surface — `s.conditional`/`s.while` `when` (incl. each `elif` branch), and
628
613
  `empty`/`notEmpty`, `isNull`/`notNull`, `between(v, lo, hi)`, `has(obj, path)`, `count(v, n)`.
629
614
  Each returns a `Comparison`, usable anywhere `expr(...)` is.
630
615
  - A condition/`where` accepts a single `expr(...)`/`cmp(...)`, an `and()`/`or()` group, an array of
631
- those (ANDed), or (for `where`) a raw `Value`. `s.conditional`/`s.while`/`s.switch`, `db.query`,
616
+ those (ANDed). `s.conditional`/`s.while`/`s.switch`, `db.query`,
632
617
  `precondition`, and the `array.*` predicates all take the same TREE shape (operators per above).
633
618
  - ⚠ `mixed(a, { or: b }, { and: c })` reproduces a container whose terms do NOT all join the
634
619
  same way — pulled workspaces contain it. **Do not author it** (export warns `condition.mixed`). The
@@ -656,11 +641,10 @@ Importing a def into a browser bundle or a Node script — for `getPath()`, `get
656
641
  no Node built-ins, so a bundler drops unused SDK exports. But importing a **def** for its
657
642
  `getPath()`/`verb`/`getUrl()`/`getChannel()` also pulls whatever its `stack` references:
658
643
  the `s.*`/`c.*` factory CALLS run at module load to BUILD it. Types are free.
659
- ⚠ A FLOOR — **~267 kB minified (~65 kB gzipped)** for the FIRST def; splitting modules
660
- never removes it. The floor is the RUNTIME, not the def: a second or much richer def
661
- adds ~2 kB, so trimming a def does not shrink it.
644
+ The first def costs **~267 kB minified (~65 kB gzipped)**; the floor is the RUNTIME, not the def:
645
+ each further def adds ~2 kB, so splitting or trimming defs does not help.
662
646
  Fix: `npx @xano/sdk routes <entry> --emit xano/routes.gen.ts` (`paths` is an accepted alias) — verbs, paths, and sockets as
663
- plain data importing NOTHING, still compile-checked: `routePath("GET blog/{slug}", { slug })`
647
+ plain data importing NOTHING, still compile-checked: `routePath("GET blog/{slug}", { slug })`, `routeQuery("GET search", input)` (the GET query string, path params dropped),
664
648
  `channelPath("rooms/{room_id}", { room_id })`, `socketUrl("chat", baseUrl)` (tenant base
665
649
  URLs lifted to `wss://h/ws/<tenant>:<canonical>`), `mcpUrl("notes_mcp", baseUrl)` (an MCP
666
650
  server's address to show a user or hand a client; browser JS cannot call it). A rename is a type error, not a 404.
@@ -669,38 +653,43 @@ Importing a def into a browser bundle or a Node script — for `getPath()`, `get
669
653
  `"<channel key> <message name>"`: `type NewListing = RouteInputs["POST listings"]`. A
670
654
  frontend types bodies, channel params and payloads from these, not `InferInput` on a def;
671
655
  keep `InferInput` in code that already imports defs. They match `InferInput`, except a
672
- `dbLink` input appears as the linked table's columns (what the server accepts). Responses
656
+ `dbLink` input is the linked table's columns, and an `input.file()` a `Blob`
657
+ (multipart). Responses
673
658
  are not in the file: `InferResponse` on an `import type` of the def.
674
659
  Runtime validation: `npx @xano/sdk marketplace install zod` adds `@xano-sdk/zod`, which writes
675
660
  `ROUTE_SCHEMAS`/`CHANNEL_SCHEMAS`/`MESSAGE_SCHEMAS` into the file under the same keys, each
676
661
  checked against its type at typecheck; the file then imports `zod`, never `@xano/sdk`.
677
- - **Verifying a def outside a bundler.** Inside a bundler (Vite/webpack) importing a
678
- query def to read `getPath()`/`verb` works directly. To spot-check from Node, run a REAL
679
- file with `tsx <file.ts>` **from inside the project root** — not `tsx -e "import …"`
680
- (its CJS-preparse mis-resolves the package `exports` map → ERR_PACKAGE_PATH_NOT_EXPORTED),
681
- and not bare `node file.ts` (chokes on the `.js`-specifier intra-workspace imports the
682
- xanosdk CLI's own loader resolves). Running from outside the project root also breaks
683
- the `@xano/sdk` specifier resolution.
684
-
685
- **Reading the injected backend URL.** `npx @xano/sdk deploy <entry> --static <dir>` writes the deployed env's URL
686
- into every html document: a prerendered build serves a different one per
687
- route, and a route without the global renders fine while every call goes to the wrong
688
- origin. Read it at runtime with a build-time fallback:
662
+ - **Verifying a def outside a bundler.** Inside a bundler (Vite/webpack), import the def and read
663
+ `getPath()`/`verb` directly. From Node, run a REAL file with `tsx <file.ts>` **from inside the project root**.
664
+ Not `tsx -e "import …"` (mis-resolves the package `exports` map → ERR_PACKAGE_PATH_NOT_EXPORTED),
665
+ not bare `node file.ts` (cannot resolve the `.js`-specifier intra-workspace imports), and not from
666
+ outside the project root (the `@xano/sdk` specifier does not resolve).
667
+
668
+ **Reading the injected backend URL.**
669
+
670
+ - `npx @xano/sdk deploy <entry> --static <dir>` writes the deployed env's URL into every html
671
+ document. A prerendered build serves a different one per route; a route without the global
672
+ renders fine while every call goes to the wrong origin.
673
+ - Read it at runtime with a build-time fallback:
689
674
  const HOST = (typeof window !== 'undefined' && window.XANO_HOST) || import.meta.env.VITE_XANO_HOST;
690
- The scaffold's `lib/api.ts` types it (`interface Window { XANO_HOST?: string }` — `undefined` in dev)
691
- and exports this as a `string`, `XANO_HOST`; outside a scaffold declare the global yourself.
692
- In LOCAL DEV there is no injected global, so the fallback is what answers: set
693
- `VITE_XANO_HOST` in a `.env.local` beside `.env.example` at the PROJECT ROOT. The
694
- scaffold's vite config sets `envDir` there (its `root` is `frontend/`, and Vite
695
- resolves `.env` files against `root`) — without it the var reads as undefined, the
696
- host falls back to '', and every call 404s off the dev server.
697
- ⚠ It is INJECTED in bracket form — `window["XANO_HOST"]="…"` — so verifying a deploy
698
- by grepping `window.XANO_HOST` matches nothing and reads as a failed inject. Grep the
699
- bare `XANO_HOST` token.
675
+ - The scaffold's `lib/api.ts` types it (`interface Window { XANO_HOST?: string }` — `undefined` in dev)
676
+ and exports this as a `string`, `XANO_HOST`; outside a scaffold declare the global yourself.
677
+ - In LOCAL DEV there is no injected global, so the fallback answers: set `VITE_XANO_HOST` in a
678
+ `.env.local` beside `.env.example` at the PROJECT ROOT. The scaffold's vite config sets `envDir`
679
+ there (its `root` is `frontend/`, and Vite resolves `.env` files against `root`); without it the
680
+ var reads as undefined, the host falls back to '', and every call 404s off the dev server.
681
+ - It is injected in bracket form — `window["XANO_HOST"]="…"` — so grepping a deploy for
682
+ `window.XANO_HOST` matches nothing. Grep the bare `XANO_HOST` token.
683
+
700
684
  **Frontend without the backend.** `npx @xano/sdk publish <dir> [--to <backend>]` uploads an
701
685
  already-built directory and nothing else — no compile, no import (scaffold script
702
686
  `npm run xano:deploy:frontend`). A Xano Engine (`--to local`, or bare after a local
703
687
  deploy) serves it, server half included, at `http://<prefix>.localhost:<port>`.
688
+ The injected `XANO_HOST` is the DESTINATION's URL, so one build published to two
689
+ destinations serves two different documents. `--release <name>` checks only that the
690
+ release exists; `--branch <label>` (workspace only) refuses unless that label is LIVE —
691
+ a label match, not a content comparison. `--json` reports `published` and `verified` separately.
692
+
704
693
  **Server-rendered SvelteKit.** `adapter()` from `@xano/sdk/sveltekit` (needs `esbuild`) writes
705
694
  the static half at the build's root plus a server half in `.xano-ssr/`. A Xano Engine renders every
706
695
  path that is not a file through it (`load` reads the engine's own URL as `XANO_HOST` from
@@ -709,16 +698,30 @@ is not sent `.xano-ssr/`: it serves the static half and answers other paths with
709
698
  shell, where a route with a server `load` fails (no `__data.json`). A scaffolded project configures
710
699
  SvelteKit in `vite.config.ts`'s `sveltekit({ adapter })`, where `svelte.config.js` is ignored.
711
700
  ⚠ `.xano-ssr/server.js` inlines `$env/static/private` values; it is never served (`/.xano-ssr/` answers 404).
712
- The injected `XANO_HOST` is the DESTINATION's URL, so one build published to two
713
- destinations serves two different documents. `--release <name>` checks only that the
714
- release exists; `--branch <label>` (workspace only) refuses unless that label is LIVE —
715
- a label match, not a content comparison. `--json` reports `published` and `verified` separately.
716
- **Displaying a stored file.** A file column comes back as `{ path, name, type, size,
717
- meta, access, url }`. ⚠ Do NOT use its `url`: on a tenant-scoped environment that field
718
- addresses the instance host WITHOUT the `/tenant/<name>` segment and 404s, silently —
719
- as a broken `<img>`, with every API assertion still passing. Build the URL from `path`
720
- instead: `fileUrl(row.avatar, HOST)` returns `null` for
721
- an absent file and is correct on an ephemeral and an instance workspace alike.
701
+
702
+ **Displaying a stored file.** A file column comes back as `{ path, name, type, size, mime,
703
+ meta, access, url }` — `mime` is the exact media type (`image/png`), `type` only the coarse
704
+ kind (`image`). Do not use its `url`: on a tenant-scoped environment it addresses the
705
+ instance host without the `/tenant/<name>` segment and 404s (a broken `<img>`; API
706
+ assertions still pass). Build the URL from `path`: `fileUrl(row.avatar, HOST)` returns `null`
707
+ for an absent file and is correct on an ephemeral and an instance workspace alike.
708
+
709
+ **Consuming a streaming response.** A `responseType: "stream"` query emits Server-Sent Events —
710
+ `Content-Type: text/event-stream`, one `data: <json>` frame per `s.api.stream({ value })` call,
711
+ each with an `id:` line that is a millisecond timestamp (ids REPEAT within a ms, so do not rely on
712
+ `Last-Event-ID` for exactly-once resume). The query's own `response` is not sent. Read it with
713
+ `EventSource`:
714
+ const es = new EventSource(`${HOST}/api:<canonical>/stream/basic`);
715
+ es.onmessage = (e) => { const chunk = JSON.parse(e.data); /* … */ };
716
+ es.onerror = () => es.close(); // EventSource is GET-only and reconnects on its own
717
+ For POST or auth headers, a `fetch` + `response.body.getReader()` loop instead, splitting the text
718
+ on the blank-line (`\n\n`) frame delimiter and stripping the `data: ` prefix. There is no typed
719
+ client helper for the stream body, and `InferResponse` does not describe it.
720
+ **Error responses.** A failed request answers a JSON envelope `{ code, message, payload }`:
721
+ `if (!res.ok) { const { code, message, payload } = await res.json(); … }`. `code` is an
722
+ `ERROR_CODE_*` string (`ERROR_FATAL` for an engine error), `message` the human text (⚠ EMPTY
723
+ on a `db` NotFound), `payload` a precondition's structured detail (`""`/absent otherwise).
724
+ The `error_type` → HTTP status and `code` mapping is in `llms/fields.md`.
722
725
 
723
726
  # Toolchain modules
724
727
 
@@ -728,20 +731,23 @@ an absent file and is correct on an ephemeral and an instance workspace alike.
728
731
  `xano/index.ts`. An installed one runs on `export` and `deploy` (after the compile,
729
732
  before the upload) and is verified, never rewritten, under `--frozen-lock`. Config
730
733
  lives in this project's `package.json` `"xanosdk"` block, keyed by package name.
731
- ⚠ `marketplace install <pkg>` is not just `npm install`: it asks the module its questions
732
- and writes that block plus the `.gitattributes` lines it contributes. A module that
733
- arrived any other way (a plain `npm install`, a merged PR) is configured by running that
734
- same command on it; until then `export`/`deploy` report it unconfigured and it runs on
735
- shipped defaults. `marketplace reinstall <pkg>` re-asks with the current settings as the
736
- defaults and re-enables a disabled one; `marketplace remove <pkg>` drops block, lines and
737
- dependency together — a plain `npm uninstall` leaves the block, and a package it names
738
- that is no longer installed fails every `--frozen-lock` run.
734
+
735
+ - `marketplace install <pkg>` is not just `npm install`: it asks the module its questions
736
+ and writes that block plus the `.gitattributes` lines it contributes. It also adds the
737
+ module's non-SDK peers (e.g. `zod`) as direct dependencies.
738
+ - A module that arrived any other way (a plain `npm install`, a merged PR) is configured by
739
+ running that same command on it; until then `export`/`deploy` report it unconfigured and it runs on
740
+ shipped defaults.
741
+ - `marketplace reinstall <pkg>` re-asks with the current settings as the defaults and
742
+ re-enables a disabled one.
743
+ - `marketplace remove <pkg>` drops block, lines and dependency together. A plain
744
+ `npm uninstall` leaves the block, and a package it names that is no longer installed
745
+ fails every `--frozen-lock` run.
739
746
 
740
747
  **A module's section of `xano/routes.gen.ts`.** A module with a `routesManifest` hook (types:
741
748
  `@xano/sdk/plugin`) writes a block between `// xanosdk:begin <pkg>` and `// xanosdk:end <pkg>`
742
749
  after the core sections, on every write of the file (`routes --emit`, `xano:routes`, `pull`,
743
750
  `generate`, `marketplace install|reinstall|remove`). Edits inside the block are overwritten.
744
- Install also adds the module's non-SDK peers (e.g. `zod`) as direct dependencies.
745
751
  The hook is synchronous and pure: given
746
752
  the request inputs under the manifest's keys and its config, it returns `{ imports?, source }`,
747
753
  imports as bare package names (`@xano/sdk*`, relative and `node:` are refused). A module that
@@ -762,34 +768,54 @@ core sections still refresh; under `routes --emit --strict` it is fatal. `@xano-
762
768
  - `Value is less than the minimum value of 1` (HTTP 400) — a `db.get` given `0` in an editor-authored workspace (SDK field-match `db.get` answers 200 + null). `llms/statements-data.md`.
763
769
  - `Invalid op: <op>` — a `cmp` operator (`in`, `like`, …) in a RUNTIME condition, which takes the `expr` set only; write `or(expr(...), expr(...))`. `llms/kinds-core.md`.
764
770
  - `Unsupported param format` / `Unsupported parameter reference` — an aggregate or `eval` `name` that is not a bare column, or a bare `eval` name for a joined column. `llms/statements-data.md`.
765
- - `ParseError: Invalid value for param` (HTTP 400) — `contains`/`@>`/`overlaps` on a text column (use `includes`), or a joined column qualified without `tableAlias`. `llms/statements-data.md`.
771
+ - `ParseError: Invalid value for param` (HTTP 400) — `contains`/`@>`/`overlaps` on a text column (use `includes`, for scalar text only: a list column 500s), or a joined column qualified without `tableAlias`. `llms/statements-data.md`.
766
772
  - `ERROR_FATAL: <Type> does not exist: <type>:<n>` — `s.api.call`/`s.task.call`/`s.trigger.call`/`s.workflow_test.call` outside a workflow test; share logic via `defineFunction` + `s.function.run`. `llms.txt`.
767
773
  - `ERROR_FATAL "Unable to decode."` — a populated JSON string where the engine expects `c.obj`'s form; write `c.obj({...})` or `obj({...})`. `llms/values.md`.
774
+ - `ERROR_FATAL "Invalid zip"` on `s.zip.view_contents`/`extract` of an uploaded `input.file` — the CLIENT-supplied Content-Type was not `application/zip` (the bytes are not checked; curl's `-F` default is `application/octet-stream`). Send `new File([…], "x.zip", { type: "application/zip" })`. A wrong password (`Extraction failed (wrong password?)`) and a non-zip both 500 — wrap the call in `s.try_catch`. `llms/statements-runtime.md`.
775
+ - `ERROR_FATAL "Infinite recursion detected. Please fix."` — `s.function.run`/`.call` nested past ~25 deep in one request (the engine's variable-stack limit), even for correct bounded recursion. Recurse iteratively (`s.while` over an explicit list) or batch. `llms/statements-calls.md`.
768
776
  - `Precondition failed.` in place of your message — `error` was a bare string; pass `c.text("…")`. `llms/fields.md`.
769
777
  - `Param: token - Text filter requires an integer, float, string or boolean value` — `s.api.call` `auth.token` given a tagged `Value`; it must be a bare string. `llms/statements-calls.md`.
770
778
  - Every `s.db.add` into one table 400s naming a column while complaining about its VALUE — the column is named `run`. `llms.txt`.
771
- - HTTP 200 with an EMPTY body where `0` was expected — a bare `returnType: "count"` of zero; wrap it as `{ count: ref("n") }`. `llms/statements-data.md`.
779
+ - HTTP 200 with an EMPTY body where `0` was expected — a bare `returnType: "count"` of zero can answer either; wrap it as `{ count: ref("n") }`. `llms/statements-data.md`.
772
780
  - HTTP 200 with `[]` from a `db.query` that matches rows — a paged query (`metadata: true`, the default) whose `output` names bare columns; the selection applies to the ENVELOPE, so prefix them (`items.<column>`) or set `metadata: false` inside `paging`. `llms.txt`; `llms/statements-data.md`.
773
781
  - Every field mapped off an `s.api.request` result reads `null` — the upstream answered an error (a 403 for a missing `User-Agent` is the common one) and its body arrived as ordinary `response.result`; send a `User-Agent` and gate on `response.status`. `llms/statements-calls.md`.
774
782
  - A lambda returns error TEXT with HTTP 200 (`Could not resolve "node:crypto"`, an undefined-binding message) — the body threw; use the preloaded globals, the surface's bindings, and `capture`. `llms/lambda.md`.
775
783
  - `Unable to locate request.` (404) on an endpoint that deployed — a lowercase verb, a `.` in the name, or a CORS `mode` typo that dropped the whole API group. `llms/kinds-core.md`.
776
784
  - A browser call fails on a missing `access-control-allow-origin` while deploy looks fine — CORS `mode: "custom"` with `"*"` or an unmatched origin. `llms/kinds-core.md`.
777
- - 403 `Forbidden: Origin not allowed` from an MCP server URL — the request came from a browser; MCP endpoints refuse every `Origin`, so call them server-side. `llms/kinds-agent-mcp.md`.
778
- - `ERROR_FATAL` `The free model is not available in this process.` — an `xano-free` agent run on the Xano Engine on this machine; it runs only on Xano's cloud. `llms/kinds-agent-mcp.md`.
785
+ - `ERROR_FATAL` `The free model is not available in this process.` — an `xano-free` agent run on a Xano Engine; it runs only on Xano's cloud. `llms/kinds-agent-mcp.md`.
786
+ - `Not supported. Please upgrade your Xano instance.` (HTTP 403) — a capability the instance lacks; on the Xano Engine on this machine, every `s.storage.sign_private_url` answers it. Test it with `deploy --ephemeral`. `llms/fields.md`.
787
+ - An MCP `tools/call` answers `isError: true` with `Unable to get successful response from executing tool` — the tool's run failed without a usable `{code, message}`, and the authored message is dropped. Common cause: a tool reading `auth()` behind an entry naming no auth table (`export()` warns `toolset.tool-reads-auth-ungated`); wrap it `{ tool: <handle>, auth: <auth table> }`. `llms/kinds-agent-mcp.md`.
779
788
  - A websocket is closed right after the handshake — a refused `connect` gate: an empty/falsy return, a crash, or a gating trigger with no `response`. `llms/triggers.md`.
780
789
  - `to_throw failed - response is ok` around an auth-refused call — `ERROR_CODE_ACCESS_DENIED` carries no message; the auth gate is not reachable from a workflow test. `llms/tests.md`.
781
790
  - Output reads `Hi [object Object]` — a tagged value inside a JS template literal; compose at runtime with `withFilters` + `fl.concat`. `llms.txt`.
782
791
 
783
792
  ### Build-time and tooling failures
784
793
 
785
- - `export --strict` fails on a warning whose shape is meant (a fixture pinning a hazard) — accept it on ITS def only with `diagnostics: { allow: ["<code>"] }`, which takes any warning code that def raised (never an error) on every def kind. Accepted warnings are still listed: `export({ accepted: [] })`, `--json` `accepted[]`. An allowed code the def no longer raises warns `diagnostics.allow-unused`.
794
+ - `export --strict` fails on a warning whose shape is meant (a fixture pinning a hazard) — accept it on ITS def only: add `diagnostics: { allow: ["<code>"] }`, which takes any warning code that def raised, on any def kind (warnings only, never an error). Accepted warnings are still listed: `export({ accepted: [] })`, `--json` `accepted[]`. An allowed code the def no longer raises warns `diagnostics.allow-unused`.
786
795
  - `must be ES modules` — package.json says `"type": "commonjs"`; set `"type": "module"`. `llms.txt` Quickstart.
787
796
  - A response types as `StackTupleWidened` — a `Statement[]` helper was spread into the stack; return `statements(...)`. `llms.txt`; `llms/statements-runtime.md`.
788
797
  - `ERR_PACKAGE_PATH_NOT_EXPORTED` — `tsx -e "import …"`, or running from outside the project root; run a real file with `tsx <file.ts>` from the root. `llms/client.md`.
789
798
  - `Missing statement: mvp:placeholder` on import — an unconfigured slot in a pulled tree; replace it with the statement it stands in for. `llms/legacy.md`.
790
- - A CLI command fails under `--json` or piped (unless stdout carries data): stdout is `{ ok: false, error: { code, message, exitCode, details?, suggestion? } }`, as does a failed release write. Codes: `SDK_SEED_IN_STATIC` (`details.leaks[]` → `publicSeed`), `SDK_EXPORT_INVALID` (`details.diagnostics[]`, `--strict` too), `SDK_DRIFT`, `SDK_BRANCH_TAKEN`, `SDK_BRANCH_LIVE`, `SDK_RELEASE_NAME_TAKEN`, `SDK_RELEASE_FILES_NOT_CARRIED`, `SDK_LIVE_BRANCH_MISMATCH` (`details.conflictsWith`), `SDK_IDENTITY_CONFLICT`, `SDK_KIND_CONFLICT`, `SDK_PRUNE_OUT_OF_SCOPE`, `SDK_IMPORT_REFUSED`, `SDK_SHARED_SCHEMA_CHANGE`, `SDK_CONSTRAINT_VIOLATION`, `SDK_CREDENTIAL_REJECTED` (`details`: `{ profile, credentialType, instance, workspaceId, signIn }`; ids null on a refused env refresh), `SDK_WORKSPACE_CHANGED` (deploy over objects edited in Xano since the last sync; `details.objects`; pull first or `--overwrite`), `SDK_USAGE` (`details.reason: "needs-confirmation"`: run its `Re-run as`), `SDK_ERROR`. Landing refusal `details.refused`: identityConflict, renamePending, kindConflict, uniqueViolation, tableTrigger, importInProgress, importRefused, pruneOutOfScope. `warnings[]` / `details.warnings` / `accepted[]` entries: `{ code, message, subject? }` (`subject`: the def's `{ kind, name }`). Backend documents add `selector` and `workspaceId`.
791
799
  - A CLI command reports `could not reach <url>: fetch failed (<code>)` — blocked egress, not a bad credential; fix it before `npx @xano/sdk login`, which rotates a single-use refresh token.
792
800
 
801
+ ### CLI failure documents
802
+
803
+ A CLI command that fails under `--json` or piped (unless stdout carries data) writes `{ ok: false, error: { code, message, exitCode, details?, suggestion? } }` to stdout, as does a failed release write. Codes:
804
+
805
+ | `code` | `details` |
806
+ |---|---|
807
+ | `SDK_SEED_IN_STATIC` | `details.leaks[]` → `publicSeed` |
808
+ | `SDK_EXPORT_INVALID` | `details.diagnostics[]`, `--strict` too |
809
+ | `SDK_LIVE_BRANCH_MISMATCH` | `details.conflictsWith` |
810
+ | `SDK_CREDENTIAL_REJECTED` | `{ profile, credentialType, instance, workspaceId, signIn }`; ids null on a refused env refresh |
811
+ | `SDK_WORKSPACE_CHANGED` | `details.objects`: objects edited in Xano since the last sync. Pull first or deploy `--overwrite`. |
812
+ | `SDK_USAGE` | `details.reason: "needs-confirmation"`: run its `Re-run as` |
813
+ | `SDK_DRIFT`, `SDK_BRANCH_TAKEN`, `SDK_BRANCH_LIVE`, `SDK_RELEASE_NAME_TAKEN`, `SDK_RELEASE_FILES_NOT_CARRIED`, `SDK_IDENTITY_CONFLICT`, `SDK_KIND_CONFLICT`, `SDK_PRUNE_OUT_OF_SCOPE`, `SDK_IMPORT_REFUSED`, `SDK_SHARED_SCHEMA_CHANGE`, `SDK_CONSTRAINT_VIOLATION`, `SDK_ERROR` | — |
814
+
815
+ - Landing refusal `details.refused`: identityConflict, renamePending, kindConflict, uniqueViolation, tableTrigger, importInProgress, importRefused, pruneOutOfScope.
816
+ - `warnings[]` / `details.warnings` / `accepted[]` entries: `{ code, message, subject? }` (`subject`: the def's `{ kind, name }`).
817
+ - Backend documents add `selector` and `workspaceId`.
818
+
793
819
  ### CLI exit codes
794
820
 
795
821
  A failure document's `exitCode` matches.
@@ -819,9 +845,10 @@ Named input sets run against one object, with assertions on its response — the
819
845
  - `name` is unique within the object and is the key a statement's `mock` resolves against; a duplicate throws.
820
846
  - `id` defaults to a derivation from the owning object plus the name. A pulled test carries the id Xano minted, emitted explicitly.
821
847
  - `datasource` defaults to `""` — an EMPTY datasource. Any other value names one the engine CLONES before the run; `"live"` warns `test.live-datasource` on the owning def.
822
- - ⚠ That empty default means **no `table({ seed })` rows exist while a unit test runs**, exactly as for a `workflowTest()` — every `db` read misses, so `resp("0.id")` fails though the deployed endpoint returns those rows. **To read `table({ seed })` rows on an EPHEMERAL**, set `datasource: "live"`: there it holds only the seed fixtures (plus rows `--keep-data` kept); the run's writes are dropped. `diagnostics.allow` accepts its warning. ⚠ `datasource` is STORED, not a per-run flag — a test left on `"live"` clones the REAL database once it runs against an instance, so clear it before you promote. Otherwise create the rows INSIDE the run (a `defineFunction` fixture the stack calls first) or `mock` the read.
848
+ - That empty default means **no `table({ seed })` rows exist while a unit test runs**, as for a `workflowTest()`: every `db` read misses, so `resp("0.id")` fails though the deployed endpoint returns those rows. Create the rows INSIDE the run (a `defineFunction` fixture the stack calls first) or `mock` the read.
849
+ - **To read `table({ seed })` rows on an EPHEMERAL**, set `datasource: "live"`: there it holds only the seed fixtures (plus rows `--keep-data` kept); the run's writes are dropped. `diagnostics.allow` accepts its warning. ⚠ `datasource` is STORED, not a per-run flag: a test left on `"live"` clones the REAL database once it runs against an instance, so clear it before you promote.
823
850
  - `input` is `{ <input name>: Value }` — tagged values (`c.*`, `ref`, …), never plain JS scalars.
824
- - `token` runs the test as an authenticated caller. A pull does NOT bring it back: it is an expiring credential, reported as a deliberate omission.
851
+ - `token` runs the test as an authenticated caller. A pull does NOT bring it back: it is an expiring credential, reported as a deliberate omission. A token is signed per instance and expires: a literal one passes only on the backend that minted it, fails `Invalid token.` anywhere else, and commits a live credential to source. Keep `token` for a throwaway local check; for `query({ auth })` logic use the `defineFunction` route under **What a `workflowTest()` run actually sees**.
825
852
 
826
853
  ### Assertions: `expect.*`, not `s.expect.*`
827
854
 
@@ -829,7 +856,10 @@ Named input sets run against one object, with assertions on its response — the
829
856
  - Subject first — argument order is the assertion: `expect.to_equal(resp(), c.int(2))`.
830
857
  - `resp()` is the response under test; `resp("id")` drills, `resp("a-b")` takes the bracket escape.
831
858
  - Subject only: `to_be_defined`, `to_not_be_defined`, `to_be_empty`, `to_be_null`, `to_not_be_null`, `to_be_true`, `to_be_false`, `to_be_in_the_future`, `to_be_in_the_past`.
859
+ - ⚠ `to_be_in_the_past`/`to_be_in_the_future` compare at WHOLE-SECOND resolution and treat the SAME second as neither — a timestamp taken during the request under test (`c.now()`, a `created_at` the endpoint just wrote) fails `to_be_in_the_past` nearly every run. Assert `expect.to_be_less_than(resp("ts"), c.now())` instead (or `to_be_defined` plus a range).
832
860
  - Subject + operand: `to_equal`, `to_not_equal`, `to_be_greater_than`, `to_be_less_than`, `to_contain`, `to_start_with`, `to_end_with`, `to_match` (operand is a delimiter-wrapped pattern — build it with `c.regex`).
861
+ - `to_be_empty` passes ONLY for `""`, `[]` and `{}` — `0`, `null` and `false` FAIL it; use `to_be_null` for null and `to_equal(…, c.int(0))` for zero.
862
+ - `to_equal`/`to_not_equal` compare LOOSELY: `"5"` equals `5`, and `5` equals `5.0`. To pin a value's TYPE, assert on a filter (`withFilters(resp("x"), fl.is_text())`), not `to_equal`.
833
863
  - `expect.to_be_within(subject, min, max)` — both bounds EXCLUSIVE; a subject equal to either fails.
834
864
  - `expect.to_throw(exception?)` takes NO subject. With an argument the error message must CONTAIN that text (case-insensitive substring); with none, any error passes. `exception` is a `Value` — `expect.to_throw(c.text("Wrong password"))`, not a bare string (a bare one fails to compile with TS2345).
835
865
 
@@ -848,14 +878,23 @@ A statement returns a value instead of doing its work, for one named test.
848
878
 
849
879
  ### What a `workflowTest()` run actually sees
850
880
 
851
- The run is isolated in ways that make a correct test fail for reasons the failure message does not name.
881
+ Isolation rules; each fails a correct test with a misleading message.
852
882
 
853
- - The run uses an EMPTY datasource by default (`datasource: ""`), so **no `table({ seed })` rows exist while it runs** (same as a unit test, above): a read of seeded row 1 fails with its own precondition message, not an empty-database error. Build fixtures INSIDE the test, or set `datasource: "live"` under the ephemeral-only rule above.
854
- - `s.api.call` does NOT raise when the endpoint answers with an error. It BINDS the error envelope (`{code, message}`) to its `as` and carries on, so a later `s.expect.to_be_defined({ expr: ref("r.field") })` reports the ASSERTION while the real failure was the call, four statements up. Assert on the envelope — `s.expect.to_contain({ expr: ref("r.code"), value: c.text("ERROR_CODE_INPUT_ERROR") })` — when a call may fail. `s.function.run` raises instead; the two disagree.
855
- - `s.expect.to_throw({ body, exception? })` runs `body` in an ISOLATED var stack, so a variable bound EARLIER in the test is not visible inside it — bind what the body needs inside the body. An outer one raises `Missing var entry: <name>` there, which the test reports as `to_throw` not matching (`export()` warns). `exception` is a `Value` whose text the raised message must CONTAIN (`c.text("already exists")`, not a bare string); omit it to accept any error.
856
- - `s.expect.to_throw` catches such a call only when the error carries a MESSAGE. `ERROR_CODE_ACCESS_DENIED` arrives with an empty one, so `to_throw` around an auth-refused call reports `to_throw failed - response is ok` — which reads as a broken auth gate on a gate that works.
883
+ - The run uses an EMPTY datasource by default (`datasource: ""`), so **no `table({ seed })` rows exist while it runs** (same as a unit test): a read of seeded row 1 fails with its own precondition message, not an empty-database error. Build fixtures INSIDE the test, or set `datasource: "live"` under the ephemeral-only rule in the first section.
884
+ - `s.api.call` reports a failing endpoint by WHERE it fails, so no single assertion covers every failure. `s.function.run` raises on every failure instead.
885
+
886
+ | Failure | What `as` gets | Assert with |
887
+ |---|---|---|
888
+ | INPUT error (missing required input, wrong type) | nothing: the call RAISES and fails the test (`Missing param: msg`); later `s.expect.*` never run | `s.expect.to_throw({ body: [s.api.call({ api, input: {}, as: "r" })], exception: c.text("Missing param") })` |
889
+ | STACK error (`s.precondition`/`guard.*`) | the envelope `{ code, message, payload }`; the run carries on | `s.expect.to_contain({ expr: ref("r.code"), value: c.text("ERROR_CODE_ACCESS_DENIED") })` |
890
+ | `s.throw` | a codeless `{ payload, statement }`: `ref("r.code")` fails `Unable to locate var` | `ref("r.payload")` |
891
+
892
+ - `s.expect.to_throw` catches a call only when the error carries a MESSAGE. `ERROR_CODE_ACCESS_DENIED` arrives with an empty one, so `to_throw` around an auth-refused call reports `to_throw failed - response is ok`.
893
+ - `s.expect.to_throw({ body, exception? })` runs `body` in an ISOLATED var stack, so a variable bound EARLIER in the test is not visible inside it — bind what the body needs inside the body. An outer one raises `Missing var entry: <name>` there, which the test reports as `to_throw` not matching (`export()` warns). `exception` is a `Value` (`c.text("already exists")`), matched as in `expect.to_throw`; omit it to accept any error.
857
894
  - An endpoint's `auth` gate is NOT enforced on `s.api.call`. A `query({ auth: users })` runs anyway and fails only where its stack dereferences `auth(...)`. A stack that never touches `auth(...)` runs unauthenticated and passes.
858
895
  - Neither `auth.token` nor an `Authorization` entry in `headers` authenticates the call — a token that answers 200 over real HTTP is refused here. To cover auth-gated logic, move the body into a `defineFunction` taking the user id and `s.function.call` that; the gate itself is not reachable from a workflow test.
896
+ - Table triggers do not fire on writes made during a test run (unit or workflow); a test asserting a trigger's side effect finds 0 rows. Triggers fire only on a deployed/ephemeral instance, async after commit (`llms/triggers.md`). Test the trigger's stack directly with `s.trigger.call({ trigger, input: { new: obj({…}), old: obj({…}), action: c.text("insert"), datasource: c.text("live") } })` — a synthetic `new`/`old`/`action`; `datasource` is REQUIRED — then assert on what it wrote.
897
+ - A failing RUN's `message` is the authored message: a `s.precondition`/`guard.*` that raised inside a `.call` reports its own text (`"Bookings must start in the future."`), an `s.throw` its `name`.
859
898
 
860
899
  ### Running them
861
900
 
@@ -873,32 +912,33 @@ The run is isolated in ways that make a correct test fail for reasons the failur
873
912
  > Read when building an MCP server (tools, prompts, resources) or an `agent()`.
874
913
 
875
914
  - An MCP server serves THREE primitives, and each reaches the client differently: a `tool()` is an action the MODEL calls (it may write); a `resource()` is read-only context the client APPLICATION lists and attaches by `uri` (reference docs, a schema, one record through a `{variable}` template); a `prompt()` is a message template with arguments the USER picks by name. Context a session opens with is a `resource()`; a workflow a user starts by name is a `prompt()`; data the model must fetch on its own mid-task stays a `tool()`, since a client shows the model only the resources attached to the conversation. Register each kind (`registerTools`/`registerPrompts`/`registerResources`) and list it on the server.
876
- - `mcpServer({ name, guid?, description?, instructions?, docs?, enabled?, canonical?, spec?, tags?, history?, tools?, prompts?, resources?, oauth?, llm?, output? })` — an MCP toolset. `llm?`/`output?` are the same blocks `agent()` takes and are usually absent: an MCP server and an agent are ONE stored object distinguished by `type`. Returns a handle with `getPath()`/`getUrl(baseUrl)` for the Streamable-HTTP endpoint — `getUrl` is NOT idempotent, a `baseUrl` already carrying an `/x2/mcp/<…>/stream` path THROWS, so resolve ONCE from the instance base URL. Fires on an ephemeral. A TENANT rides AFTER the prefix (`/x2/mcp/tenant/<tenant>/<canonical>/<token>/stream`), not as a base-URL segment: `getUrl` LIFTS a `/tenant/<name>` out of the base and re-places it there, so `getUrl(window.XANO_HOST)` is correct as-is; concatenating them by hand builds an unregistered route that 404s. Pass `{ tenant }` when the base URL cannot name it (a tenant on its own domain).
877
- - ⚠ Refuses any request carrying a browser `Origin`, preflight too: 403, JSON-RPC `-32000` `Forbidden: Origin not allowed`. One with no `Origin` (curl, a server, an MCP client) is served; the bundle cannot admit an origin, so call it server-side, never from browser JS.
878
- - `tools?`: a `ToolsetToolEntry[]`. Pass the `tool()` HANDLES directly (`tools: [saveNote]`); use the `{ tool, enabled?, auth?, type?, resourceUri?, toolMeta? }` wrapper when an entry needs more. `type: "resource"` (+ a required `resourceUri`) is the LEGACY way to publish a tool as an MCP resource — author a `resource()` and list it in `resources` instead; `toolMeta` is extra metadata on a tool entry. The two payload fields are per-type and supplying the other one is refused, because the engine stores it against neither. `auth` names an auth **table** (a `table({ auth: true })` handle or its name) — per-tool, and the only gate there is. ⚠ It is also what gives the tool a CALLER, on an `agent()` exactly as on an MCP server. `auth()` inside a tool whose entry names no table does NOT return null: the call answers a normal result carrying `{"code":"ERROR_FATAL","message":""}`, so the model reads a successful tool result and reports success while nothing is written. A caller token does not rescue it — the ENTRY supplies identity. Spell it `{ tool: saveNote, auth: users }`; `export()` warns. An entry naming no tool THROWS at export; a deliberate raw `id: 0` warns and carries through.
915
+ - `mcpServer({ name, guid?, description?, instructions?, docs?, enabled?, canonical?, spec?, tags?, history?, tools?, prompts?, resources?, oauth?, llm?, output? })` — an MCP toolset. `llm?`/`output?` are the same blocks `agent()` takes and are usually absent. Returns a handle with `getPath()`/`getUrl(baseUrl)` for the Streamable-HTTP endpoint — `getUrl` is NOT idempotent, a `baseUrl` already carrying an `/x2/mcp/<…>/stream` path THROWS, so resolve ONCE from the instance base URL. Fires on an ephemeral. A TENANT rides AFTER the prefix (`/x2/mcp/tenant/<tenant>/<canonical>/<token>/stream`), not as a base-URL segment: `getUrl` LIFTS a `/tenant/<name>` out of the base and re-places it there, so `getUrl(window.XANO_HOST)` is correct as-is; concatenating them by hand builds an unregistered route that 404s. Pass `{ tenant }` when the base URL cannot name it (a tenant on its own domain).
916
+ - ⚠ The endpoint is CORS-open (serves every browser `Origin`; preflight `204`, `access-control-allow-origin: *`); per-tool `auth`/`oauth` is the only gate.
917
+ - `tools?`: a `ToolsetToolEntry[]`. Pass the `tool()` HANDLES directly (`tools: [saveNote]`); use the `{ tool, enabled?, auth?, type?, resourceUri?, toolMeta? }` wrapper when an entry needs more. `type: "resource"` (+ a required `resourceUri`) publishes a tool as an MCP resource — prefer a `resource()` listed in `resources`; `toolMeta` is extra metadata on a tool entry. `resourceUri` only with `type: "resource"`, `toolMeta` only with `type: "tool"`; the wrong one is refused. `auth` names an auth **table** (a `table({ auth: true })` handle or its name) — per-tool, and the only gate there is. ⚠ It is also what gives the tool a CALLER, on an `agent()` and an MCP server alike. `auth()` inside a tool whose entry names no table does NOT return null: the run binds `{"code":"ERROR_FATAL","message":""}`. On an `agent()` the model reads that as a successful tool result and reports success while nothing is written; over an MCP server's `tools/call` the client instead gets an `isError: true` tool error with the generic text `Unable to get successful response from executing tool`. Either way the write never happens and a caller token does not rescue it — the ENTRY supplies identity. Spell it `{ tool: saveNote, auth: users }`; `export()` warns. An entry naming no tool THROWS at export; a deliberate raw `id: 0` warns and carries through.
879
918
  - `prompts?` / `resources?`: `prompt()` / `resource()` HANDLES (or names), or a `{ prompt, enabled?, auth? }` / `{ resource, enabled?, auth? }` wrapper. `auth` names the auth table and is what gives the stack a caller: a prompt/resource reading `auth()` behind an entry with none answers every `prompts/get` / `resources/read` with `-32603 "Access Denied"` (`export()` warns `toolset.primitive-reads-auth-ungated`). Listing one target twice THROWS; two resources with one `uri` on one server fail `export()` (`mcp.resource-uri-duplicate`). MCP-server only — `agent()` takes tools only.
880
919
  - `history?` is the server tier for its tools, prompts AND resources alike; an object's own `history` wins. The workspace tier (`workspaceConfig({ history })`) has `prompt` and `resource` keys, both default on.
881
920
  - `oauth?`: per-server sign-in; omit and nothing changes. Union on `mode`; `authTable` (REQUIRED, auth `table()` handle or name) is whose row the signed-in user is — `auth()` on the whole server, `t.auth` in its trigger. Hosted (the platform is the authorization server): `{ mode: "hosted", authTable, loginUrl }` — clients are sent to `loginUrl` (YOUR page, which is also the consent screen) with `mcp_request`; show `s.mcp.oauth.request`, sign the user in, then your endpoint calls `s.mcp.oauth.complete` with their `decision` and the page redirects to the URL it binds. External (your IdP issues tokens): `{ mode: "external", authTable, issuer, column, audience?, audienceAck?, claim?, claimAck?, preset?, allowedClientIds? }` — token `claim` (default `sub`) matched against `column`; `preset` is `auth0|clerk|workos|entra|okta|cognito|generic`. `loginUrl`/`issuer`/`audience` take `env("NAME")` (resolved per environment).
882
- - `export()` FAILS: hosted without `loginUrl` (`mcp.oauth-hosted-incomplete`); external without `issuer`/`column` (`mcp.oauth-external-incomplete`); `preset: "clerk"` without `allowedClientIds` (`mcp.oauth-preset-client-ids`); `claim` other than `sub`/`oid`/`email` without `claimAck` (`mcp.oauth-claim-unacked` — users can edit it at most providers). Unknown `mode`/`preset` THROWS; so do the dropped `consent`/`branding`/`trustedClients`.
921
+ - `export()` FAILS: hosted without `loginUrl` (`mcp.oauth-hosted-incomplete`); external without `issuer`/`column` (`mcp.oauth-external-incomplete`); `preset: "clerk"` without `allowedClientIds` (`mcp.oauth-preset-client-ids`); `claim` other than `sub`/`oid`/`email` without `claimAck` (`mcp.oauth-claim-unacked` — users can edit it at most providers). Unknown `mode`/`preset` THROWS, as do `consent`/`branding`/`trustedClients` (not options).
883
922
  - `prompt({ name, guid?, description?, docs?, title?, icons?, tags?, history?, input?, stack?, response?, responseShape?, middleware? })` — an MCP prompt; takes `registerPrompts`. `input` is the prompt's arguments (each field's `description`/`required`/enum `values` reach the client; enum values also answer completion requests). `response`: a text value is ONE user message; a list of `{ role: "user" | "assistant", content }` is sent in order, `content` a string or an MCP content block: `s.set_var("m", obj({ list: [obj({ role: c.text("user"), content: ref("body") })] }))`, `response: ref("m.list")`. Without `response` or a top-level `s.return`, `prompts/get` fails.
884
923
  - `resource({ name, uri, guid?, description?, docs?, mimeType?, title?, icons?, annotations?, tags?, history?, input?, stack?, response?, responseShape?, middleware? })` — an MCP resource; takes `registerResources`. Clients address it by `uri`, never `name`.
885
924
  - `uri`: a literal (`"docs://readme"`, no `input`) or an RFC 6570 LEVEL-1 template (`"orders://{region}/{order_id}"`). It must start with a scheme; each `{variable}` is letters/digits/`_`, one per brace pair, never two adjacent. `input` must be EXACTLY the template's variables, each a single `text`/`int`/`decimal`/`bool`/`enum`/`email`/`uuid` — anything else THROWS. A value that does not convert is refused before the stack runs.
886
925
  - `response`: a string is returned as text; non-UTF-8 content (a file, binary) as a base64 blob. `mimeType?` omitted → derived from what the stack returns.
926
+ - Not found: a resource has no built-in miss path. Returning a `db.get` result straight through on a miss is an EMPTY SUCCESS — the client attaches an empty document (`text: ""`, `mimeType: "text/plain"`), not an error. Gate it: `s.precondition({ expr: expr(ref("note"), "!=", c.null()), error_type: "notfound", error: c.text("no such note") })` gives a real `resources/read` error (JSON-RPC `-32602`), but ⚠ the AUTHORED message is dropped — the client sees only the generic `Not Found` (unlike a `tool()` precondition).
887
927
  - `annotations?`: `{ audience?: ("user" | "assistant")[], priority?: 0..1, lastModified?: ISO 8601 string }`.
888
928
  - MCP metadata, on `tool`/`prompt`/`resource`: `title?` (display name clients show instead of `name`); `icons?: { src, mimeType?, sizes?, theme? }[]` — `src` is `https:` (≤ 2048 chars), a base64 `data:` URI of PNG/JPEG/WebP (≤ 64 KiB), or `hostedFile("./icon.png", import.meta.url)`, a repo file served at each backend's own absolute URL (a pull keeps the `/vault/…` path); SVG, `http:` and every other scheme THROW; `mimeType` is `image/png|jpeg|webp`, `sizes` a list (`["48x48"]`, `["any"]`), `theme` `light|dark`. Tool only: `annotations?: { readOnlyHint?, destructiveHint?, idempotentHint?, openWorldHint? }` — hints; an unset one is derived by the platform — and `output?`, a structured-output schema in the `input` grammar: a returned plain object then reaches the client as `structuredContent` plus a text copy, and a result that does not match is a tool error naming the field.
889
929
  - `s.mcp.elicit({ key, message, input?, as? })` — ask the MCP client's user mid-call; binds `{ action: "accept" | "decline" | "cancel", content? }` (`content` only on accept, keyed by the `input` field names). `key`: a stable name unique in the stack; `message`: string or value. `input` is the form: a FLAT set of `text`/`email`/`date`/`int`/`decimal`/`bool`/`enum` fields (an enum may be a list); nested objects, files, JSON, timestamps, `password` and `sensitive` fields THROW. Works in tool, prompt and resource stacks.
890
930
  - ⚠ The WHOLE stack re-runs from the top when the user answers — everything BEFORE an elicit runs once per round trip, so ASK FIRST, then act. A write before an elicit (`s.db.*` writes, raw SQL, a non-GET `s.api.request`, `s.util.send_email`, `s.function.run`/`.call`, `s.tool.call`) makes `export()` warn `mcp.write-before-elicit`; accept a deliberate one per def with `diagnostics: { allow: ["mcp.write-before-elicit"] }`. An elicit inside `s.db.transaction` commits the transaction's earlier writes on every round trip.
891
- - Input is collected only from clients on MCP `2026-07-28` or later that declare form elicitation. Every other caller — an older client, a debug run, an agent, a workflow test — gets `{ action: "cancel" }` and the stack carries on, so ALWAYS handle `cancel`. A runtime error inside an async function run.
931
+ - Input is collected only from clients on MCP `2026-07-28` or later that declare form elicitation. Every other caller — an older client, a debug run, an agent, a workflow test — gets `{ action: "cancel" }` and the stack carries on, so ALWAYS handle `cancel`. Inside an async function run, `s.mcp.elicit` is a runtime error.
892
932
  - `s.mcp.progress({ progress, total?, message? })` — report progress to a client that asked for it (a no-op otherwise); values never go backwards (a lower `progress` is sent as the last one).
893
933
  - `s.mcp.oauth.complete({ request, decision, unsafe_user_id?, as? })` — run by the endpoint your `loginUrl` page calls after sign-in; `request` is the page's `mcp_request`. Signs in the CALLER (`auth()`, an `authTable` row whose session token is under 10 minutes old) and binds the single-use URL (text) to redirect to. `decision` (`"approve" | "deny"`, REQUIRED) is what the user chose on your page. ⚠ `unsafe_user_id` names the row directly, skipping the caller checks — anyone reaching that endpoint signs in as that user.
894
934
  - `s.mcp.oauth.request({ request, as? })` — a pending sign-in's verified details for your `loginUrl` page to show before the user approves: `{ client_name, client_logo, callback_host, client_verified, server_name }`. Does not consume it.
895
935
  - `s.mcp.oauth.revoke({ mcp_server, user_id? | grant_id? | all?, as? })` — end hosted sign-ins on a server: EXACTLY ONE of `user_id`, `grant_id`, `all: c.bool(true)`, else `export()` fails (`mcp.oauth-revoke-target`). Binds `{ revoked }`.
896
936
  - `agent({ name, guid?, description?, docs?, enabled?, canonical?, tags?, history?, llm, tools?, output? })` — an LLM orchestrator. No top-level `instructions`/`prompt`/`spec` — the prompt lives under `llm`. Invoke from a stack with `s.ai.agent.run({ agent, args })`.
897
- - `llm` (REQUIRED): typed provider settings, a discriminated union on `type` (`"xano-free" | "anthropic" | "openai" | "google-genai"`). Shared fields: `systemPrompt?`, `maxSteps?` (default `5`), and `prompt?` XOR `messages?` (genuinely exclusive: both is a type error and throws — the engine stores ONE `prompt_type`, so one would be dropped); plus provider fields (`apiKey?`, `model?`, `temperature?`, `reasoningEffort?`, …). String fields accept Twig placeholders — `{{ $args.x }}` for run inputs (the `args` of `s.ai.agent.run`), `{{ $env.NAME }}` for env vars.
937
+ - `llm` (REQUIRED): typed provider settings, a discriminated union on `type` (`"xano-free" | "anthropic" | "openai" | "google-genai"`). Shared fields: `systemPrompt?`, `maxSteps?` (default `5`), and `prompt?` XOR `messages?` (mutually exclusive; both is a type error and throws); plus provider fields (`apiKey?`, `model?`, `temperature?`, `reasoningEffort?`, …). String fields accept Twig placeholders — `{{ $args.x }}` for run inputs (the `args` of `s.ai.agent.run`), `{{ $env.NAME }}` for env vars.
898
938
  - `xano-free` runs only on Xano's cloud: on the Xano Engine on this machine a run fails `ERROR_FATAL` `The free model is not available in this process.` — use a keyed provider there.
899
- - `tools?`: same `ToolsetToolEntry[]` as `mcpServer` — bare `tool()` handles, or a `{ tool, enabled?, auth? }` wrapper when one needs `enabled`/`auth`. A tool reading `auth()` MUST use the wrapper naming the auth table — a bare handle runs it with no caller (see `mcpServer`'s `tools?`).
900
- - `output?`: `{ schema: Record<string, input.*>, enabled? }` — structured-output schema. `schema` is a named-field record authored with the `input.*` catalog, exactly like a `defineFunction`/`query` `input:` map (the stored `structuredOutputsSchema` is the same wire shape as function inputs). e.g. `output: { schema: { priority: input.enum(["low","high"]), summary: input.text() } }`. When you pass the agent *handle* to `s.ai.agent.run({ agent })`, `.result` is typed straight from this schema — no `resultShape` witness needed (the shape is declared once). `resultShape` remains only to override that, or to type an agent referenced by bare name.
901
- - **Run + read recipe (`s.ai.agent.run`):** bind the run to a var (`s.ai.agent.run({ agent, args, allowToolExecution: c.bool(true), as: "run" })`) — it produces a rich envelope, and the completion is at **`.result`**. Read one structured field with a dotted ref (`response: ref("run.result.priority")`) or the whole completion (`ref("run.result")`, typed from `output.schema`); persist it in a later step the same way (`s.set_var("summary", ref("run.result.summary"))`). `args` is a plain object of run inputs (`{ topic: inp("topic") }` — raw literals are fine, e.g. `{ max_steps: 3 }`) surfaced to the agent as `{{ $args.topic }}`. `.toolCalls` is the FINAL step's calls only (often `[]`); every call is a `.steps[].content[]` entry of `type: "tool-call"`. ⚠ An agent with tools needs `allowToolExecution: c.bool(true)` on the run: unset, its tools are OFF and it answers without them (warns `stack.agent-tools-off`).
939
+ - `tools?`: same `ToolsetToolEntry[]` as `mcpServer` — bare `tool()` handles, or a `{ tool, enabled?, auth? }` wrapper when one needs `enabled`/`auth`. A tool reading `auth()` needs the wrapper naming its auth table (see `mcpServer`'s `tools?`).
940
+ - `output?`: `{ schema: Record<string, input.*>, enabled? }` — structured-output schema. With `tools`, the run executes them first, then shapes its answer into the schema. `schema` is a named-field record authored with the `input.*` catalog, exactly like a `defineFunction`/`query` `input:` map. e.g. `output: { schema: { priority: input.enum(["low","high"]), summary: input.text() } }`. When you pass the agent *handle* to `s.ai.agent.run({ agent })`, `.result` is typed from this schema; `resultShape` only overrides that, or types an agent referenced by bare name.
941
+ - **Run + read recipe (`s.ai.agent.run`):** bind the run to a var (`s.ai.agent.run({ agent, args, as: "run" })`) — it produces a rich envelope, and the completion is at **`.result`**. Read one structured field with a dotted ref (`response: ref("run.result.priority")`) or the whole completion (`ref("run.result")`, typed from `output.schema`). `args` is a plain object of run inputs (`{ topic: inp("topic") }` — raw literals are fine, e.g. `{ max_steps: 3 }`) surfaced to the agent as `{{ $args.topic }}`. `.toolCalls` is the FINAL step's calls only (often `[]`); every call is a `.steps[].content[]` entry of `type: "tool-call"`. `allowToolExecution` defaults to true. ⚠ `c.bool(false)` does not hide the tools: the model still emits a call, the call never executes, and the run ends with an empty `result` (warns `stack.agent-tools-off`).
902
942
  - **Marketplace:** for chat history, use `@xano-sdk/chatbot`; for vector RAG, use `@xano-sdk/vector` (`tools: [vector.searchTool]`). Find add-ons with `npx @xano/sdk marketplace search <q>`.
903
943
  - Both kinds persist under the `toolset` payload key, so a same-name `agent` + `mcpServer` pair derives ONE guid and `export()` throws — give them distinct names.
904
944
 
@@ -906,8 +946,8 @@ The run is isolated in ways that make a correct test fail for reasons the failur
906
946
 
907
947
  > Read when the workspace defines a `knowledge()` item.
908
948
 
909
- - `knowledge({ name, description?, type?, mode?, enabled?, body, refs?, guid?, tags? })` — markdown shared by every AI that builds the backend: Xano's own AI reads it before it acts — the workspace's builder agent, and outside agents reading the workspace through the Meta API or MCP — and a local coding agent reads the same `.md` files in the repo; deploy and `pull` keep the copies in sync. It does NOT reach an `agent()` run by `s.ai.agent.run`, whatever its `type` or `mode`: put what such an agent must know in its `llm.systemPrompt`. Takes `registerKnowledge`.
910
- - `body` (REQUIRED): `knowledgeFile("./runbook.md", import.meta.url)` — a path to a real markdown FILE. There is no inline-string form. The path resolves relative to the MODULE THAT DECLARES the item, not the process working directory and not the workspace entry; `import.meta.url` is required and is what makes that true.
949
+ - `knowledge({ name, description?, type?, mode?, enabled?, body, refs?, guid?, tags? })` — markdown shared by every AI that builds the backend. Xano's own AI reads it before it acts: the workspace's builder agent, and outside agents reading the workspace through the Meta API or MCP. A local coding agent reads the same `.md` files in the repo; deploy and `pull` keep the copies in sync. It does NOT reach an `agent()` run by `s.ai.agent.run`, whatever its `type` or `mode`: put what such an agent must know in its `llm.systemPrompt`. Takes `registerKnowledge`.
950
+ - `body` (REQUIRED): `knowledgeFile("./runbook.md", import.meta.url)` — a path to a real markdown FILE. There is no inline-string form. The path resolves relative to the MODULE THAT DECLARES the item (not the working directory or the workspace entry), via the required `import.meta.url`.
911
951
  - `refs?`: `knowledgeDir("./runbook", import.meta.url)` — a directory whose WHOLE tree ships, recursively, paths preserved: UTF-8 text only (else refused; binary `.DS_Store` skipped), symlinks not followed. Keep the body OUT of it, or it ships as a reference file.
912
952
  - `type?`: `"skill"` (default) | `"doc"` | `"agents.md"`. `skill` and `doc` differ in how they are filed, not in what an agent receives.
913
953
  - `mode?`: `"auto"` (default) | `"always"` | `"referenced"`.
@@ -920,8 +960,8 @@ The run is isolated in ways that make a correct test fail for reasons the failur
920
960
  - `mode: "referenced"` — full body only on turns whose message names the item (bare name or `@name`).
921
961
  - `mode: "auto"` — name and `description` only; the agent loads the body when a request matches.
922
962
  - Reference files are never injected wholesale — an agent searches them on demand. That is what makes a large `mode: "auto"` item cheap.
923
- - ⚠ `mode: "always"` on a long body spends its whole length on every request, and nothing in the types says so. `"auto"` is the default for that reason. For an `auto` item `description` is ALL the agent sees until it decides to load the body, so write it to be matched against a request rather than as a title.
924
- - `name` takes letters, digits, and `/ _ - { } . ` or a space; anything else is an export error.
963
+ - ⚠ `mode: "always"` costs the full body on every request (nothing in the types flags it). For an `auto` item `description` is ALL the agent sees until it decides to load the body, so write it to be matched against a request rather than as a title.
964
+ - `name` takes letters, digits, space, and `/` `_` `-` `{` `}` `.`; anything else is an export error.
925
965
 
926
966
  # Realtime def shapes
927
967
 
@@ -932,13 +972,13 @@ The run is isolated in ways that make a correct test fail for reasons the failur
932
972
  - `enabled` defaults to **false** — the one `enabled` in the SDK that does.
933
973
  - An enabled server with no active channel still refuses the handshake.
934
974
  - `realtimeChannel({ name, server, guid?, description?, active?, input?, anonymousClients?, presence?, publish?, conversation?, delivery?, rateLimit?, tags?, history?, middleware? })`
935
- - `name` is a PATH (`"lobby"`, `"rooms/{room_id}"`); `input` types its `{param}` segments, NOT the payload. Every `{param}` MUST have a matching input, and that input must be a SCALAR and not a list (`json`/`object`/`array: true` have no URL form), or `realtimeChannel()` THROWS. `required: true` is NOT checked and is not needed — segment counts must match, so the segment is always present at join. Name charset as query (`A-Za-z0-9_-/{}`, max 200), and so is `tool`; `realtimeMessage` is NARROWER — no `/` or `{}`.
975
+ - `name` is a PATH (`"lobby"`, `"rooms/{room_id}"`); `input` types its `{param}` segments, NOT the payload. Every `{param}` MUST have a matching input, and that input must be a SCALAR and not a list (`json`/`object`/`array: true` have no URL form), or `realtimeChannel()` THROWS. `required: true` is NOT checked and not needed (segment counts must match, so the segment is always present at join). Name charset as query (`A-Za-z0-9_-/{}`, max 200); `realtimeMessage` is narrower — no `/` or `{}`.
936
976
  - Matching is STRICT: a literal segment beats a param (`rooms/lobby` and `rooms/{room_id}` coexist); segment counts must be EQUAL (`rooms/{room_id}` does NOT match `rooms/42/edit`); literals are CASE-SENSITIVE; an empty segment is REJECTED, not collapsed (a leading/trailing/doubled `/` matches nothing). `realtimeChannel()` refuses it and a partial-segment `{param}`; `getChannel()` a value outside `[A-Za-z0-9_-]`.
937
977
  - An INACTIVE channel reports the same error as a nonexistent one — deactivating leaks nothing.
938
- - `middleware?: { pre?, post? }` is the CONTAINER tier, on the channel and on the server alike — the default chain every message inherits, the same shape an api group has. Full chain: message -> channel -> server -> branch/workspace, mirroring `history`. Put a realtime auth or rate-limit guard here rather than repeating it on every `realtimeMessage`.
978
+ - `middleware?: { pre?, post? }` is the CONTAINER tier, on the channel and on the server alike — the default chain every message inherits, the same shape an api group has. Full chain: message -> channel -> server -> branch/workspace, mirroring `history`. ⚠ It cannot GUARD: a middleware that throws fails open (below).
939
979
  - `anonymousClients` also gates CONNECT: a tokenless socket connects only if an active channel of its server sets it (no server flag); each channel admits its own join.
940
980
  - `publish?: { who?: "nobody"|"anyone"|"authenticated", direct? }` — `who` defaults to `nobody`: nobody can publish until you set it. `direct` (default false) allows DIRECT messages — a frame whose `options.to = { dbo_id, row_id }` addresses one USER (`dbo_id` = the auth table's id as `s.realtime.get_session` reports it, `row_id` = the user's row id) and reaches every socket of theirs on the channel, no one else; the sender gets a receipt `{ delivered_local, direct: true }`. `direct` REPLACES `who` for such a frame rather than adding to it (`direct: true` with `who: "nobody"` delivers direct messages and refuses broadcasts); an anonymous sender is refused. A direct message is never stored in the transcript or the `at_least_once` stream, so an offline user never gets it. ⚠ An `options.to` naming no usable identity is sent as an ordinary broadcast to the whole channel where `who` admits the sender.
941
- - `conversation?: { enabled?, limit?, ttl? }` — the client-visible TRANSCRIPT replayed to a joiner (distinct from `history`, which is execution history). ⚠ `limit` DEFAULTS TO 0 AND 0 MEANS OFF: `{ enabled: true }` alone records nothing and replays nothing, silently. `ttl` is an IDLE expiry of the WHOLE transcript, refreshed by every write (an active channel never ages out; a silent one loses all of it at once) — NOT a per-message age cap.
981
+ - `conversation?: { enabled?, limit?, ttl? }` — the client-visible TRANSCRIPT replayed to a joiner (distinct from `history`, which is execution history). ⚠ `limit` DEFAULTS TO 0 AND 0 MEANS OFF: `{ enabled: true }` alone records nothing and replays nothing, silently — always pass `limit`. `ttl` is an IDLE expiry of the WHOLE transcript, refreshed by every write (an active channel never ages out; a silent one loses all of it at once) — NOT a per-message age cap.
942
982
  - `delivery?: { guarantee?: "at_most_once"|"at_least_once", perRecipient? }` — `perRecipient` is independent of the guarantee, is a NO-OP unless the channel declares a `deliver` trigger, and costs a stack PER RECIPIENT PER MESSAGE. Per-viewer redaction needs BOTH HALVES — this flag AND an active `deliver` trigger bound to the channel — and with either missing the payload is delivered UNCHANGED to everyone; `export()` warns on each half alone.
943
983
  - `rateLimit?: { messagesPerMinute? }` — 0 = unlimited, checked BEFORE the handler runs. A COST guardrail, not a security control: an anonymous client is bucketed per CONNECTION (reconnecting resets it), and it fails OPEN when its store is down.
944
984
  - `realtimeMessage({ name, channel, server?, guid?, description?, active?, auth?, deliverTo?, input?, middleware?, stack?, response?, responseShape?, history?, disabled?, tags? })` — the invocable unit (the realtime analogue of a query).
@@ -948,92 +988,90 @@ The run is isolated in ways that make a correct test fail for reasons the failur
948
988
  - **Both input surfaces read as ordinary inputs:** `inp("body")` for a payload field, `inp("room_id")` for the channel's `{room_id}`. No session lookup, no frame parsing.
949
989
  - A path param is bound ONCE at join and read from the connection thereafter, never from the frame — a sender cannot claim a room it did not join.
950
990
  - `s.realtime.get_session({ as })` — the CALLER's realtime session for the current frame. FLAT shape:
951
- - `authenticated` bool · `client_id` text (the AUTHED ROW ID as text, `""` anonymous) · `dbo_id` int (the auth TABLE's id — NOT the user's row id; `0` anonymous — to look the caller up use `client_id`. `dbo_id` is an int in the same position and typechecks, so a gate that keys on it finds no user and refuses EVERYONE) · `socket_id` int (transport id) · `channel` text (resolved path, `""` in a server trigger) · `params` object (bound path params, `{}` when none — `ref("session.params.room_id")`) · `extras` object · `opened_at` decimal.
991
+ - `authenticated` bool · `client_id` text (the AUTHED ROW ID as text, `""` anonymous) · `dbo_id` int (the auth TABLE's id, `0` anonymous) · `socket_id` int (transport id) · `channel` text (resolved path, `""` in a server trigger) · `params` object (bound path params, `{}` when none — `ref("session.params.room_id")`) · `extras` object · `opened_at` decimal · `token_error` text|null (`"expired"`/`"invalid"` when the client SENT a token that did not authenticate — it connected anonymously; `null` otherwise).
992
+ - `dbo_id` is NOT the user's row id — look the caller up by `client_id`. A gate keyed on `dbo_id` typechecks, finds no user, and refuses EVERYONE.
952
993
  - Works in a realtime MESSAGE stack and in CHANNEL and SERVER trigger stacks; off that path it degrades to an anonymous session.
953
994
  - For a path param prefer `inp("room_id")` in a MESSAGE; a lifecycle TRIGGER has only the session. Reach for the session when you need the CONNECTION (identity/extras) — "who is this sender" on an anonymous-client channel.
954
- - ⚠ THREE UNRELATED THINGS ARE CALLED A CLIENT ID: `session.client_id` (app-facing identity), `session.socket_id` (transport), and a frame's `options.client_id` (the at_least_once CURSOR handle). Conflating the first and last breaks at_least_once for anonymous clients.
995
+ - Three unrelated things are called a client id: `session.client_id` (app-facing identity), `session.socket_id` (transport), and a frame's `options.client_id` (the at_least_once cursor handle). Conflating the first and last breaks at_least_once for anonymous clients.
955
996
  - `s.realtime.publish({ server, channel, data, message?, authTable?, authId? })` — the PUSH direction: originate a server-authored event onto a channel from ANY stack, no client frame first.
956
997
  - `server` is the handle or its NAME (resolved by name, not guid); `channel` is the FILLED-IN path (`channel.getChannel({ room_id: 42 })`), never the template — a constant still carrying `{param}` THROWS at author time, and a constant `server`/`channel` naming nothing this workspace registers WARNS at export.
957
998
  - A PER-ROW path whose id is only known at runtime is built as a value, not with `getChannel()` (which needs the id at author time): `withFilters(c.text("rooms/"), fl.concat(ref("room.id")))`, or `s.set_var` + `s.text.prepend`. A computed `channel`/`server` — a `ref`/`inp`, or a constant carrying a filter chain — is left alone by the export check.
958
999
  - DELIVERY-ONLY — fanned out as-is; does NOT invoke a `realtimeMessage()` handler even when `message` names one (a channel `deliver` trigger still runs).
959
1000
  - SERVER-AUTHORITATIVE — bypasses `publish.who`, which governs CLIENTS. Authorize in your own stack.
960
1001
  - ⚠ FAIL-SOFT — a missing/disabled server or dead bus is swallowed engine-side, so a mis-targeted publish is SILENT with no result to check.
961
- - `authTable`/`authId` are ASSERTED attribution on the frame — not a credential, nothing validates them.
1002
+ - `authTable`/`authId` are ASSERTED attribution on the frame — not a credential, nothing validates them. They land in `_meta.as`, NOT in `payload`.
1003
+ - `s.realtime.kick({ server, channel, authTable, authId, reason? })` — remove one user from one channel: every socket of `authTable`/`authId` (the identity is REQUIRED) leaves the FILLED-IN `channel` path, on every node, through the same steps as a client `leave` (the `leave` trigger, a `presence_leave`), and receives `{ action: "leave", channel, payload: { left: true, kicked: true, reason } }`. The socket stays CONNECTED and keeps its other channels. Call it wherever you revoke a membership the `join` gate admitted.
1004
+ - NOT fail-soft (unlike `publish`): an unknown server, a missing identity, or a dead bus FAILS the stack — a kick that silently did nothing would leave the member subscribed.
962
1005
  - **Client recipe (derive, never hardcode):**
963
1006
  - `server.getUrl(baseUrl)` → `wss://<host>/ws/<canonical>` — accepts the `https://…` instance base URL and normalizes the scheme. `channel.getChannel({ room_id: 42 })` → `"rooms/42"`, the path that goes in a frame's `channel` field. Both throw rather than guess. A canonical is minted by `npx @xano/sdk export <entry> --lock`.
964
- - Auth is a bearer token passed as the websocket SUBPROTOCOL: `new WebSocket(url, token)`. No token = an anonymous client, admitted only where `anonymousClients: true`.
1007
+ - Auth is a bearer token passed as the websocket SUBPROTOCOL: `new WebSocket(url, token)`. No token = an anonymous client, admitted only where `anonymousClients: true`. ⚠ An INVALID, tampered, or EXPIRED token still connects — ANONYMOUSLY, with no error and no close (presence lists it `authenticated: false`) — and says why: `session.token_error` is `"expired"` or `"invalid"`, and a refusal the socket meets for being anonymous names the token: `{ message: "Your token has expired. Reconnect with a fresh token.", token_error: "expired", reason: "Anonymous clients cannot join this channel" }`. On an error frame carrying `token_error`, refresh the token and reconnect. For a hard refusal at connect, gate with a `realtimeServerTrigger` `connect` (`allowed: session.token_error == null`, or `session.authenticated` → a 4401 close).
965
1008
  - Frames are JSON `{ action: "join"|"leave"|"broadcast"|"ack"|"ping"|"presence", channel, type?, payload?, options?, id? }`. `broadcast` REQUIRES `type`: a `realtimeMessage` of that channel, else refused `Unknown message type`. You must `join` before you may `broadcast`, and the server's context is ready only a moment after `open` — an immediate first frame is refused.
966
1009
  - `options` is `{ to?, client_id?, channel? }` — `to: { dbo_id, row_id }` makes the frame a direct message (needs `publish.direct`), `client_id` is the at-least-once cursor handle, and `options.channel` WINS over a top-level `channel`.
967
1010
  - ⚠ KEEP THE SOCKET ALIVE: an idle connection is REAPED after ~10 minutes. A LISTEN-ONLY client (a feed or dashboard that joins and rarely publishes) MUST send `{ action: "ping" }` (answered `pong`) or any frame periodically or it silently drops.
968
- - Server frames: `join` (ack `{ joined: true, params }`, + `cursor`/`resumed` on at_least_once) · `message` · `replay` · `broadcast` · `presence_full`|`presence_join`|`presence_leave` · `conversation_start`|`conversation_end` (replayed frames flagged `conversation: true`) · `pong` · `ack` · `error`.
969
- - ⚠ `broadcast` is a RECEIPT to the sender, not a delivery confirmation: `payload.delivered_local` counts recipients on the ANSWERING NODE ONLY, not the channel. It also carries `id` on at_least_once and `dropped: true` when the handler returned null.
970
- - `error` carries `payload.message`, plus `code`/`limit`/`retry_after` when rate limited. `rate_limited` is the ONLY code — do NOT switch on `code`.
1011
+ - Server frames: `join` (ack `{ joined: true, params }`, + `cursor`/`resumed` on at_least_once) · `message` · `replay` · `broadcast` · `presence_full`|`presence_join`|`presence_leave` · `conversation_start`|`conversation_end` (replayed frames flagged `conversation: true`) · `pong` · `ack` · `error`. An `s.realtime.publish` frame also carries `_meta`: `{ injected: true }` (asserted marker for a server-authored event vs a relayed peer), plus `as: { dbo_id, row_id }` from `authTable`/`authId`.
1012
+ - `broadcast` is a RECEIPT to the sender, not a delivery confirmation: `payload.delivered_local` counts recipients on the ANSWERING NODE ONLY, not the channel. It also carries `id` on at_least_once and `dropped: true` when the handler returned null.
1013
+ - `error` carries `payload.message`, plus `code`/`limit`/`retry_after` when rate limited. `rate_limited` is the only code — do not switch on `code`.
971
1014
  - An `error` is a per-frame refusal, NOT a disconnect — EXCEPT a failed handshake and a REFUSED `connect` trigger, which each send one and then CLOSE with code 4401.
972
- - **Tenant instances (isolated DB):** a tenant's realtime objects live in the TENANT's database, so BOTH halves of a client must name the tenant.
973
- - Socket: `server.getUrl(base, { tenant })` → `/ws/<tenant>:<canonical>`. ⚠ A bare canonical on a tenant host resolves against the INSTANCE workspace instead.
974
- - That colon form is PECULIAR TO THE SOCKET. Every other tenant URL gives the tenant its OWN segment — the HTTP half of the same client is `https://<host>/tenant/<tenant>/api:<canonical>/…`. NO request header is required for either.
975
- - Because the shapes differ, `getUrl` TRANSLATES a tenant base URL instead of concatenating: pass the `https://<host>/tenant/<name>` that `npx @xano/sdk status` prints (and that deploy injects as `window.XANO_HOST`) and the tenant is LIFTED into the socket form. So `getUrl(window.XANO_HOST)` needs no `{ tenant }`, and a CONFLICTING `{ tenant }` alongside it throws.
976
- - ⚠ `getUrl`/`socketUrl` are NOT idempotent — a `baseUrl` that already carries a `/ws/<…>` path THROWS. Resolve ONCE from the http(s) base; never feed a result back in.
1015
+ - **Tenant instances (isolated DB):** a tenant's realtime objects live in the TENANT's database, so both the socket and the HTTP half of a client must name the tenant. No request header is required for either.
1016
+ - Socket: `server.getUrl(base, { tenant })` → `/ws/<tenant>:<canonical>` — the colon form is socket-only; HTTP gives the tenant its own segment (`https://<host>/tenant/<tenant>/api:<canonical>/…`). ⚠ A bare canonical on a tenant host resolves against the INSTANCE workspace instead.
1017
+ - `getUrl` TRANSLATES a tenant base URL: pass the `https://<host>/tenant/<name>` that `npx @xano/sdk status` prints (and deploy injects as `window.XANO_HOST`) and the tenant is LIFTED into the socket form, so `getUrl(window.XANO_HOST)` needs no `{ tenant }`; a conflicting `{ tenant }` alongside it throws.
1018
+ - `getUrl`/`socketUrl` are NOT idempotent — a `baseUrl` that already carries a `/ws/<…>` path THROWS. Resolve ONCE from the http(s) base; never feed a result back in.
977
1019
  - Still pass `{ tenant }` explicitly for a tenant on its OWN DOMAIN — the hostname carries it for HTTP, but there is nothing in the URL for the socket to lift.
978
- - ⚠ Tokens are tenant-scoped (audience `<tenant>:<license>`, not the bare license), so one minted through the instance workspace is REJECTED by a tenant's realtime server — authenticate and dial through the same tenant.
1020
+ - Tokens are tenant-scoped (audience `<tenant>:<license>`, not the bare license), so one minted through the instance workspace is REJECTED by a tenant's realtime server — authenticate and dial through the same tenant.
979
1021
  - **Presence frames** (a `presence: true` channel only):
980
- - `presence_full` carries `payload.members`, an ARRAY: at join it EXCLUDES the receiver (first joiner: `[]`), on a re-request it includes it. `presence_join`/`presence_leave` carry a single `payload.member`.
1022
+ - `presence_full` carries `payload.members`, an ARRAY: it INCLUDES the receiver, at join (first joiner: itself) and on a re-request. `presence_join`/`presence_leave` carry a single `payload.member`. `members` is in NO guaranteed order (not join order): sort it yourself if order matters.
981
1023
  - A member is `{ id, dbo_id, authenticated, extras, joined_at }`: `id` the auth row id as a string (`"0"` anonymous), `dbo_id` the auth table's id (`0` anonymous), `extras` the connection's extras (`[]` if none), `joined_at` epoch SECONDS.
982
1024
  - Render `presence_full`, then apply deltas. One member per authenticated identity (a second tab fires no `presence_join`); anonymous ones all have `id` `"0"`, never collapsed.
983
1025
  - Join order: `join` ack → `presence_full` → (others get `presence_join`) → conversation replay → `replay` frames.
984
1026
  - A joined client re-requests it with `{ action: "presence", channel }`, answered to the SENDER only; a socket that never joined is REFUSED.
985
- - **Conversation frames — the transcript hydrates the client, so DO NOT build a hydration endpoint.**
1027
+ - **Conversation frames** — the transcript hydrates the client (no hydration endpoint); editable or moderated content needs one of the two shapes below.
986
1028
  - On a `conversation` channel the replay is PUSHED automatically at join, unasked: `conversation_start` (`payload.count`) → the last `limit` messages, each a normal `action: "message"` frame carrying its ORIGINAL `type` and `payload` plus `conversation: true` and the original `ts` → `conversation_end`.
987
- - Render `message` frames identically either way: no fetch or table read is needed to paint the initial view.
988
- - ⚠ `{ enabled: true }` alone is a no-op: `limit` defaults to 0 and 0 means RETAIN NONE (see `conversation` above) — always pass `limit`.
989
1029
  - The POST-HANDLER broadcast payload IS the stored transcript row — a handler must broadcast everything the UI needs to render a past message (author name, id, `created_at`). Nothing else is replayed.
990
1030
  - The transcript is a capped ring (`limit`, `ttl`), not storage: persist to a table only for durability, search, or reads beyond it.
1031
+ - ⚠ APPEND-ONLY: the transcript records EVERY fanned-out frame — `s.realtime.publish` frames included, not only `"channel"`/`"others"` handler returns — and no entry can be edited or removed. A message deleted or EDITED in the DB is still replayed to every later joiner: both its original and any edited broadcast stay in the ring until `limit`/`ttl` evicts them, including across a `--keep-data` redeploy — so for editable/moderated content the transcript LEAKS retracted bodies. An ephemeral `deliverTo: "others"` frame (a typing indicator) also takes a ring slot, so a busy signal evicts real messages.
1032
+ - Two safe shapes for editable/moderated chat: (a) turn `conversation` OFF, hydrate the initial view from a table endpoint, and keep the socket for live frames only; or (b) keep bodies OUT of the frames — publish ids only and read current bodies from a table — and put ephemeral signals (typing) on a SEPARATE channel with no `conversation`.
991
1033
  - **`delivery.guarantee: "at_least_once"` is a CLIENT CONTRACT, not just a channel setting.**
992
1034
  - The client must ACK what it receives — `{ action: "ack", channel, id }`, confirmed by `{ action: "ack", channel, payload: { cursor } }`.
993
1035
  - ⚠ An ANONYMOUS client must ALSO send a durable `options.client_id` in its JOIN frame (once; later acks need not repeat it). WITHOUT one it has no cursor, its acks are SILENTLY IGNORED, and it degrades to at_most_once. An AUTHENTICATED client is keyed by identity and needs no `client_id`.
994
- - The missed gap arrives after join as `replay` frames, oldest-first, each with an `id` to ack. ⚠ A first join gets `cursor: "0"`: the WHOLE retained stream replays, repeating a `conversation` transcript.
1036
+ - The missed gap arrives after join as `replay` frames, oldest-first, each with an `id` to ack. A first join gets `cursor: "0"`: the WHOLE retained stream replays, repeating a `conversation` transcript.
995
1037
  - DISTINCT from the conversation transcript: `conversation_*` is the SHARED "what was said before I arrived", `replay` is the PER-CLIENT "what I missed while disconnected". Both may be on.
996
1038
  - How far back `replay` reaches is sized by `conversation.ttl` (here a REAL per-message age cut, and it BEATS `limit`), else `conversation.limit`, else 1000 — even on a channel with no transcript enabled.
997
- - **What a message handler RETURNS decides delivery, and the failure directions are NOT symmetric.**
1039
+ - **What a message handler RETURNS decides delivery:**
998
1040
  - A returned value fans out per `deliverTo` and becomes the transcript row.
999
1041
  - Returning NULL delivers NOTHING — the supported way to veto a message (the sender is told `dropped: true`).
1000
1042
  - A payload REJECTED by the declared `input` also delivers nothing; the detail goes ONLY to the sender.
1001
- - ⚠ But a handler that CRASHES FAILS OPEN: the sender's ORIGINAL, UNVALIDATED payload is broadcast to the channel unchanged. A handler doing redaction or authorization must NOT be the only thing between client input and subscribers.
1043
+ - ⚠ A handler that CRASHES FAILS OPEN — a failed `s.precondition`/`guard.*` (even in an `s.function.run` target), a throwing middleware, a runtime error: the sender's ORIGINAL, UNVALIDATED payload is broadcast unchanged (`s.throw` DROPS it). To veto, set the response var to `c.null()`.
1002
1044
 
1003
1045
  # Triggers
1004
1046
 
1005
1047
  > Read when authoring any trigger. A trigger's `stack` is a callback rather than the plain array every other kind takes, so the shape does not carry over.
1006
1048
 
1007
- **A trigger's `stack` is a callback — `stack: (t) => [...]` — to read a trigger
1008
- input** (a plain list works when it reads none). That's the one
1009
- shape that doesn't carry over from the other kinds: a trigger has no
1010
- user-declared `input`, so its inputs are **implied by type** (fixed by Xano,
1011
- not editable) and arrive through the typed **stack handle** `t` — you can't
1012
- reference them without it. (`response` too — a callback, or a plain value that
1013
- reads none.) `t` exposes exactly that trigger type's inputs; a wrong
1014
- name is a compile error, not a runtime surprise. The seven trigger types are
1049
+ A trigger has no user-declared `input`: its inputs are **implied by type** and arrive through the typed
1050
+ **stack handle** `t`, so `stack` is a callback — `stack: (t) => [...]` (a plain list works when it
1051
+ reads none; `response` likewise). `t` exposes exactly that trigger type's inputs; a wrong name is a
1052
+ compile error. The seven trigger types are
1015
1053
  distinct root factories (not a namespace): `{tableTrigger, realtimeServerTrigger,
1016
1054
  realtimeChannelTrigger, mcpServerTrigger, agentTrigger, workspaceTrigger,
1017
1055
  errorTrigger}({ name, guid?, description?, active?, tags?, history?, ... })`.
1018
1056
  `history` is per trigger (omit to inherit the workspace's `history.trigger`, default
1019
1057
  off); a trigger's own failure reaches the error log only while it is on.
1020
1058
 
1021
- - `tableTrigger({ name, table?, datasources?, actions?: {insert?,update?,delete?,truncate?}, stack })` — database/table trigger. `t.new` / `t.old` are the row **after** / **before** the change; `t.action` (`insert|update|delete|truncate`), `t.datasource`. Bind `table` to a `table()` handle and `t.new("col")` / `t.old("col")` are typed to that row (misspelled column = compile error). ⚠ Insert's `old` and delete's `new` are `{}`, not null — branch on `t.action`, not a null check. Config-only (no response).
1059
+ - `tableTrigger({ name, table?, datasources?, actions?: {insert?,update?,delete?,truncate?}, stack })` — database/table trigger. `t.new` / `t.old` are the row **after** / **before** the change; `t.action` (`insert|update|delete|truncate`), `t.datasource`. Bind `table` to a `table()` handle and `t.new("col")` / `t.old("col")` are typed to that row (misspelled column = compile error). ⚠ Insert's `old` and delete's `new` are `{}`, not null, and drilling one (`t.old("col")`) RAISES and aborts the run — branch on `t.action` with an `s.conditional`. Config-only (no response). ⚠ A table trigger runs AFTER the write COMMITS, from an event queue, so it is NOT the usual in-transaction trigger: it CANNOT veto the write (a top-level `s.precondition`/`s.throw` fails only inside the trigger — visible via an `errorTrigger` when history is on, never to the writing request, which already answered 200 with the row stored) and its own edits do NOT reach that request's response (a `slug` it computes lands on the row a moment later, not in the POST body). Validate in the WRITING stack or a shared `defineFunction`; use the trigger only for after-the-fact side effects. ⚠ Writes made WHILE a trigger runs fire NO table triggers (the runner disables them for the whole stack), on the SAME or any OTHER table — so a trigger may safely edit its own table (no loop), but triggers do NOT chain: a trigger on `orders` that writes `stock` fires no `stock` trigger. Chain by calling the follow-up logic as a `defineFunction`.
1022
1060
  - `realtimeServerTrigger({ name, realtimeServer, actions?: {connect?,disconnect?}, stack?, response?, responseShape? })` — realtime SERVER lifecycle (a client connecting to / disconnecting from the server, not a message). Inputs: `t.action` (`connect|disconnect`), `t.realtime_server`, `t.client`. Bind `realtimeServer` to a `realtimeServer()` handle (or its name).
1023
- - `connect` GATES the connection — a denial sends an `error` and CLOSES the socket with code 4401 before it is ever ready, so it is a real front door, not an observer; same return shape as a channel `join` below (EMPTY/FALSY DENIES — INCLUDING a gating trigger with NO `response`, which returns nothing and so refuses every client).
1024
- - A CRASH DENIES too — a gate that cannot answer must not admit. Both failure modes lock the door, so plan for a self-inflicted LOCKOUT (an unguarded drill into a null `db.get` raises → everyone refused), not a breach.
1061
+ - `connect` GATES the connection — a denial sends an `error` and CLOSES the socket with code 4401 before it is ever ready. Same return shape as a channel `join` below (EMPTY/FALSY DENIES — including a gating trigger with NO `response`, which refuses every client).
1062
+ - A CRASH DENIES too. Failure is a LOCKOUT, not a breach (an unguarded drill into a null `db.get` raises → everyone refused).
1025
1063
  - Gating is OPT-IN: a server with no `connect` trigger accepts every connection.
1026
- - `disconnect` is OBSERVATIONAL (return ignored, throws swallowed — cleanup must always complete).
1064
+ - `disconnect` is OBSERVATIONAL (return ignored, throws swallowed).
1027
1065
  - Both are SERVER-scoped, so `s.realtime.get_session` works but carries no channel path and no bound params.
1028
- - `realtimeChannelTrigger({ name, channel, actions?: {join?,leave?,deliver?}, stack?, response?, responseShape? })` — realtime CHANNEL lifecycle. Inputs: `t.action` (`join|leave|deliver`), `t.channel`, `t.payload`, `t.client`. Bind `channel` to a `realtimeChannel()` handle — a bare path is NOT accepted (it is unique only within its server). The three actions have DIFFERENT postures, and the posture decides what the stack should return:
1029
- - `join` GATES the join (it runs before membership) — return `{ allowed: c.bool(true) }` (optional `reason` reaches the client) or any truthy value to admit, and an EMPTY OR FALSY RETURN DENIES, so a stack that just falls through — or a gating trigger with NO `response` — refuses everyone, and a CRASH DENIES too. ONCE the object carries an `allowed` key admission needs STRICTLY `true` — `1`/`"yes"` there DENIES. Compute it as `c.expression("…")` or a `ref()` to a `set_var` boolean (`expr()` is not a `response` value). That is the inverse of a crashing message, which still delivers, and of `deliver` below.
1030
- - A lifecycle trigger's inputs are PINNED to those four, so a channel PATH PARAM is NOT among them — `inp("room_id")` RAISES, which crashes the gate and so REFUSES every client; take the param from `s.realtime.get_session` (`ref("session.params.room_id")`).
1066
+ - `realtimeChannelTrigger({ name, channel, actions?: {join?,leave?,deliver?}, stack?, response?, responseShape? })` — realtime CHANNEL lifecycle. Inputs: `t.action` (`join|leave|deliver`), `t.channel`, `t.payload`, `t.client`. Bind `channel` to a `realtimeChannel()` handle — a bare path is NOT accepted (it is unique only within its server). Each action has its own return posture:
1067
+ - `join` GATES the join (it runs before membership) — return `{ allowed: c.bool(true) }` (optional `reason` reaches the client) or any truthy value to admit, and an EMPTY OR FALSY RETURN DENIES, so a stack that just falls through — or a gating trigger with NO `response` — refuses everyone, and a CRASH DENIES too. ONCE the object carries an `allowed` key admission needs STRICTLY `true` — `1`/`"yes"` there DENIES. Compute it as `c.expression("…")` or a `ref()` to a `set_var` boolean (`expr()` is not a `response` value). This is the inverse of a crashing message, which still delivers, and of `deliver`. ⚠ It runs ONCE: revoking access later (a deleted membership row) does NOT unsubscribe the open socket. Evict it from the endpoint that revokes the membership with `s.realtime.kick` (`llms/kinds-realtime.md`).
1068
+ - A lifecycle trigger's inputs are PINNED to those four, so a channel PATH PARAM is NOT among them — `inp("room_id")` RAISES, which crashes the gate and so REFUSES every client; take the param from `s.realtime.get_session` (`ref("session.params.room_id")`). ⚠ It is RAW TEXT — path params are not validated or coerced at join (`rooms/abc` joins an `input.int()` channel; `session.params.room_id` is `"42"`, a string), so a numeric gate must CAST it (`fl.to_int()`) and refuse a non-numeric value itself. The declared type is enforced only when a MESSAGE reads `inp(...)`, per frame, after the join.
1031
1069
  - A gate establishes NO auth: `auth("id")` reads 0 when authenticated, `ref("auth.id")` raises — identity is `t.client("permissions.row_id")` or the session. A SERVER connect/disconnect has no channel, so no params at all.
1032
1070
  - `leave` is OBSERVATIONAL (return ignored, throws swallowed).
1033
- - `deliver` GATES delivery PER RECIPIENT — the per-viewer redaction tool and the most expensive action here (a stack per recipient per message), and it needs `delivery.perRecipient` on the channel to run at all — BOTH HALVES are required, so a `deliver` trigger on a channel without the flag NEVER RUNS and every subscriber receives the UNREDACTED payload (no error, no log line); `export()` warns on each half alone.
1034
- - **`deliver`'s RETURN VALUES DO NOT READ LIKE A FILTER:** ONLY an explicit NULL drops the message for that recipient; an OBJECT replaces that recipient's payload; ANYTHING ELSE — INCLUDING `false`, `0`, `""` — DELIVERS IT UNCHANGED, as does a crash. So `return false` from a yes/no redaction check SENDS the message it was written to suppress — return null instead.
1071
+ - `deliver` GATES delivery PER RECIPIENT — the per-viewer redaction tool, a stack per recipient per message. ⚠ It runs only when the channel sets `delivery.perRecipient` (`llms/kinds-realtime.md`); without it every subscriber receives the UNREDACTED payload, with no error.
1072
+ - ⚠ `deliver`'s return values do not read like a filter: ONLY an explicit NULL drops the message for that recipient; an OBJECT replaces that recipient's payload; anything else — including `false`, `0`, `""` — delivers it unchanged, as does a crash. Return null, not `false`, to suppress.
1035
1073
  - The delivered payload arrives NESTED, so read `t.payload("<field>")`, and `t.client` is the SENDER while `s.realtime.get_session` describes the RECIPIENT this run is for.
1036
- - `mcpServerTrigger({ name, mcpServer, stack?, response?, responseShape? })` / `agentTrigger({ name, agent, stack?, response?, responseShape? })` — toolset connection. Bind with the `mcpServer()`/`agent()` def handle (or its name) — it resolves to the toolset guid at export. Raw numeric `objId` is the escape hatch, rarely right: ids are assigned at import, so a handle passed to `objId` is a type error, and binding nothing deploys a trigger that never fires. Inputs: `t.toolset` (`t.toolset("name")`), `t.tools`; an MCP server's also `t.prompts`/`t.resources`: return one filtered to narrow what the connection lists, omit it to list all — and `t.auth`, the signed-in user `{dbo, id, extras}` when the server has `oauth` (null otherwise). Response-bearing; the default returns every list input.
1074
+ - `mcpServerTrigger({ name, mcpServer, stack?, response?, responseShape? })` / `agentTrigger({ name, agent, stack?, response?, responseShape? })` — toolset connection. Bind with the `mcpServer()`/`agent()` def handle (or its name) — it resolves to the toolset guid at export. Raw numeric `objId` is a rarely-right escape hatch; binding nothing deploys a trigger that never fires. Inputs: `t.toolset` (`t.toolset("name")`), `t.tools`; an MCP server's also `t.prompts`/`t.resources`: return one filtered to narrow what the connection lists, omit it to list all — but ⚠ a keyed response MUST keep `toolset` and `tools` (omitting either breaks the server for every client) — and `t.auth`, the signed-in user `{dbo, id, extras}` when the server has `oauth` (null otherwise). Response-bearing; the default returns every list input.
1037
1075
  - `workspaceTrigger({ name, actions?: {branch_live?,branch_merge?,branch_new?}, stack? })` — branch lifecycle. Inputs: `t.to_branch`, `t.from_branch`, `t.action`. Config-only.
1038
1076
  - `errorTrigger({ name, stack? })` — error-signature trigger. Inputs: `t.event` (`new|regression|fixed`), `t.id`, `t.signature`, `t.error` (`t.error("code")`/`t.error("message")`), `t.caller`, `t.statement`, `t.actor`, `t.count`, `t.first_seen`, `t.last_seen`, `t.fixed_at`. Config-only.
1039
1077
 
@@ -1044,7 +1082,12 @@ off); a trigger's own failure reaches the error log only while it is on.
1044
1082
  Array blocks (an `if`/`transform` is applied per item):
1045
1083
 
1046
1084
  - `s.array.map({ source, as?, transform? })` — `transform` is either a per-item `Value` expression (each item maps to that value) or a **record of values** (each item maps to an object with those keys), or a list of `{ key, value }` pairs, for a key computed per item or two rows sharing one. Use `ref("$this")` for the item and `ref("$index")` for its position. A `transform` value, filter arguments included, can read `ref("$this.<path>")` and any outer stack variable or input. These are THIS statement's own bindings, in a value expression — not the JavaScript lambda contract (see **Lambda bodies**), which binds a different set per surface and is written with `lam.fn`.
1047
- - `s.array.union({ source, with, as?, transform? })` — set-union two arrays. `with` is REQUIRED; omitted → `Unable to locate input: `.
1085
+ - `s.array.union({ source, with, as?, transform? })` — set-union two arrays. `with` is REQUIRED; omitted → `Unable to locate input: `. `transform` is a per-item DEDUPE KEY over `$this`, not a map: the result keeps the original items, first occurrence wins (`transform: ref("$this.id")` unions records by `id`).
1086
+ - **Array predicates** (`s.array.filter`/`filter_count`/`find`/`find_index`/`has`/`every`/`partition`) share one shape: `{ expr, if, as }`. The `if` comparison reads the current item as `ref("$this")` (or `ref("$this.<path>")`) and resolves any outer var/input; `$index` is bound ONLY inside `partition`, not the others. Results: `filter` → the matching list; `filter_count` → an int; `find` → the item or `null` on a miss; `find_index` → the index or `-1` on a miss (on an OBJECT source it returns the matching KEY, e.g. `"x"`); `has` → a bool; `every` → a bool, `true` on `[]`; `partition` → `{ "true": [...], "false": [...] }` (STRING keys). ⚠ An OBJECT source iterates its VALUES (keys dropped from `filter`'s result), and a null, omitted or scalar source behaves like `[]`. The predicate uses the engine's LOOSE comparison, so `"abc" > 3` and `"1" = 1` are both true.
1087
+ - **Set ops** `s.array.difference`/`intersection` take `{ expr, value, by?, as }` (`s.array.union`'s shape is the bullet above). All three compare STRICTLY (`"3"` ≠ `3`), unlike the predicates — and they DEDUPE the source: `[1,1,2,"3"]` − `[3]` → `[1,2,"3"]`, `[1,2,2,3]` ∪ `[3,4]` → `[1,2,3,4]`. Without `by`, records compare whole; `by` is a `$this` expression (`by: ref("$this.id")`), not a column name.
1088
+ - `s.array.group_by({ expr, by?, as })` binds an OBJECT keyed by each item's `by` value (a missing key read with `{ safe: true }` groups under `""`). ⚠ WITHOUT `by` on a list of records it 500s (`Cannot access offset of type array on array`) — always pass `by` for records.
1089
+ - **In-place array mutators** `s.array.push`/`unshift`/`merge`/`pop`/`shift` take `{ name, value? }` and REWRITE the var named `name` (no `as`); `name` may be a dotted path (`"o.items"`). `pop`/`shift` on `[]` bind `null`. ⚠ `push` of a LIST appends it as ONE element (`[…, [9,9]]`) where `merge` SPREADS it in; `push` onto a scalar var throws, and onto an object var it adds numeric keys.
1090
+ - `s.object.keys`/`values`/`entries({ value, as })` on `{}`, null, an omitted var or a string all bind `[]`; on a LIST they treat the indexes as keys. `entries` yields `{ key, value }` OBJECTS (not `[key, value]` tuples), and an integer-like key comes back as a NUMBER (PHP coerces it), for all three.
1048
1091
 
1049
1092
  DB reads/writes (`table` is a def handle or name; `fieldName` defaults to the
1050
1093
  primary key `id`):
@@ -1054,56 +1097,61 @@ primary key `id`):
1054
1097
  - `s.db.del({ table, fieldName?, fieldValue, as? })` — delete by field match.
1055
1098
  - `s.db.add({ table, row?, data?, output?, as? })` — insert; `row` is a partial keyed by column.
1056
1099
  - A row CELL takes a tagged `Value`, a nested object of sub-keys, or a bare JS literal typed against that column: `row: { is_hidden: true, notes: "…" }` encodes exactly as `{ is_hidden: c.bool(true), notes: c.text("…") }`. The tag comes from the COLUMN, not the literal — `10` on an `f.decimal()` column is `const:decimal`, not `const:int` — so a literal contradicting its column is a compile error on a `f.*`-schema table (`{ is_hidden: "yes" }` on an `f.bool()` column) and throws at encode on a raw-`ColumnDef[]` one. An `f.enum()` column keeps its member union. A column with no literal form — obj/json/list/geo/vector/file — still needs `c.obj`/`c.array`.
1057
- - `null` is accepted on EVERY column, including ones that refuse every other literal, and encodes `const:null` — a write OF null, not the same as omitting the key. A column's `nullable` is not consulted at encode; the engine refuses a null it forbids.
1058
- - Omitting a key on `add` writes the column's type default — declared `default` if set, `[]` for a list, `{}` for obj/json, else `null`. That `null` is EMITTED, not what the row holds: the engine applies the column's nullability, so a `nullable` column keeps `null` and a non-nullable one lands on its type's zero value (`""`, `0`, `false`). Set the cell when the stored value matters. On `edit` an omitted key keeps its stored value.
1100
+ - `null` is accepted on EVERY column at encode and encodes `const:null`; a column's `nullable` is not consulted there. ⚠ The engine does not refuse it either: on a NON-NULLABLE column an explicit `null` is the SAME as omitting the key — it stores the column's `default`, else the type's zero value (`""`/`0`/`false`/…). Only a `nullable: true` column STORES null.
1101
+ - Omitting a key on `add` writes the column's type default — declared `default` if set, `[]` for a list, `{}` for obj/json, else `null`, which is EMITTED, not what the row holds: a `nullable` column keeps `null`, a non-nullable one lands on its type's zero value (`""`, `0`, `false`). ⚠ Except `f.date`: it stores TODAY's date, absent from `add`'s `as` — make an optional date `nullable: true`. On `edit` an omitted key keeps its stored value.
1059
1102
  - An `f.password()` cell takes the PLAINTEXT — the column hashes on write, so a pre-hashed value, or a hashing filter on the cell, stores a hash of a hash that `security.check_password` can never match.
1060
- - A `table({ seed })` cell hashes the same way: the import writes the plaintext through the column's own rules, so a seeded credential matches under `security.check_password` exactly as an added one does. Demo accounts work as fixtures — the usual caution about seed data applies, since the plaintext sits in the repo.
1103
+ - A `table({ seed })` cell hashes the same way: the import writes the plaintext through the column's own rules, so a seeded credential matches under `security.check_password` exactly as an added one does. Seeded credentials work as fixtures; their plaintext is committed to the repo.
1061
1104
  - `s.db.edit({ table, fieldName?, fieldValue, row?, data?, output?, as? })` — update by field match.
1062
- - `s.db.patch({ table, fieldName?, fieldValue, data, output?, as? })` — merge a partial. ⚠ Unlike `db.edit`'s `row`, `data` is a single object `Value` — write `obj({ unread: c.int(0) })`, not the column-keyed record `row` takes.
1063
- On these three, `output` restricts the columns of the RETURNED row only — it does not change
1105
+ - `s.db.patch({ table, fieldName?, fieldValue, data, output?, as? })` — merge a partial. ⚠ Unlike `db.edit`'s `row`, `data` is a single object `Value` — write `obj({ unread: c.int(0) })`, not the column-keyed record `row` takes. ⚠ A json/object column value is DEEP-merged key by key, not replaced: patching `{ meta: { k: 1 } }` onto `meta = { origin: "WA" }` stores `{ origin: "WA", k: 1 }`, so a patch can NEVER drop a key from a json column — use `db.edit` with `row: { meta: … }` to replace one wholesale.
1106
+ - `output` on `db.get`/`add`/`edit`/`patch` restricts the columns of the RETURNED row only — on a write it does not change
1064
1107
  what is written. Not offered on `db.del`/`db.has` (their result is a scalar) or on
1065
1108
  `db.add_or_edit` (no output envelope).
1066
1109
  - `s.db.add_or_edit({ table, fieldName?, fieldValue, row?, data?, as? })` — upsert.
1067
1110
  - `s.db.query({ table, where?, additionalWhere?, bind?, sort?, paging?, external?, returnType?, distinct?, eval?, output?, lock?, addon?, as? })` — search.
1068
- - `where` / `additionalWhere` — `expr(...)`, an `expr[]` (ANDed), or a raw `Value`. Rides `context.search`.
1069
- - ⚠ `ignoreEmpty` DROPS the predicate when the operand is empty (not zero rows). On `in` an empty list returns the UNFILTERED set, so never scope to permitted ids with it; a `bulk.delete` only it scopes throws.
1111
+ - `where` / `additionalWhere` — `expr(...)` or an `expr[]` (ANDed); never a value. Rides `context.search`.
1112
+ - ⚠ `ignoreEmpty` DROPS the predicate when the operand is empty (not zero rows). "Empty" is PHP `empty()` — `null`, `""`, `"0"`, `0`, `false`, `[]`:
1113
+ - `0`/`false` also drop it: an optional numeric/bool filter can't match zero or false (`max_price=0` returns the whole table), and an omitted `input.int()`/`input.bool()` binds `0`/`false`. Use `ignoreEmpty` only for an optional TEXT/LIST filter; for a number/bool use a `nullable: true` input + `s.conditional` on `!= null`.
1114
+ - On `in` an empty list returns the UNFILTERED set, so never scope to permitted ids with it (a `bulk.delete` only it scopes throws).
1115
+ - `not in` an empty list is the mirror trap, matching NO rows, so an exclusion filter returns nothing when nothing is excluded — guard both empty cases.
1070
1116
  - For the full operator set use `cmp(left, op, right, { ignoreEmpty? })` — `op`: `in`/`not in`/`like`/`ilike`/`between`/`contains`/`includes`/`overlaps`/`@>`/`~`/`search`/… plus the `expr` comparisons. Database-only — a runtime condition takes the `expr` set only.
1071
- - ⚠ `like`/`ilike` take the operand as the PATTERN, verbatim: a bare term matches only an exact whole-string equal, and the endpoint answers HTTP 200 with zero rows — nothing reports a problem, so a search box that matches nothing ships. For substring matching use `includes`/`not includes`, which wrap the operand in `%…%` themselves and match case-INSENSITIVELY. Prefer them over a hand-built `"%" + term + "%"`, which is non-empty even for an empty term and so defeats `ignoreEmpty`; `includes` composes with it. `contains`/`@>`/`overlaps` are JSON/array containment, not text — on a text column they 400 `ParseError: Invalid value for param`.
1117
+ - ⚠ `like`/`ilike` take the operand as the PATTERN, verbatim: a bare term matches only an exact whole-string equal, and the endpoint answers HTTP 200 with zero rows, no error. For substring matching use `includes`/`not includes`, which wrap the operand in `%…%` themselves and match case-INSENSITIVELY. Prefer them over a hand-built `"%" + term + "%"`, which is non-empty even for an empty term and so defeats `ignoreEmpty`; `includes` composes with it. `contains`/`@>`/`overlaps` are JSON/array containment, not text — on a text column they 400 `ParseError: Invalid value for param`.
1118
+ - **Filter a LIST column** (`f.text({ array: true })`) to rows that hold a value — the "posts tagged X" query — with `contains`/`overlaps` and a LIST on the right. ⚠ A SCALAR on the right 400s `Invalid value for param` every request, whether a literal (`c.text("x")`) or a scalar-typed `inp("tag")`/`ref()` (`export()` warns `db.filter-operand-invalid`) — wrap the single value in a list first. For an OPTIONAL value add `fl.filter_empty_text` so an omitted one matches nothing (not `[""]`, which `array_push` would leave): `s.set_var("tag_list", withFilters(c.array([]), fl.array_push(inp("tag")), fl.filter_empty_text()))` then `cmp(col("tags"), "contains", ref("tag_list"), { ignoreEmpty: true })`. (`in` cannot take the list column on the RIGHT — one side must be a scalar.)
1072
1119
  - Compose nested boolean logic with `and(...)` / `or(...)` groups (also available on `addon()` `where`).
1073
1120
  - An operand may be a bare value (`col`/`inp`/`ref`/`auth`/`c.*`) OR a **filtered** value (`withFilters(...)`) inline — the engine compiles the string and arithmetic filters (`trim`, `concat`, `upper`, `lower`, …) into the SQL.
1074
1121
  - ⚠ The REQUEST-TIME timestamp filters have no SQL form and kill the request with a bare fatal naming nothing: `epochms_transform`, `epochms_add_ms`, `epochms_add_secs`, `epochms_date`, `epochms_from_format`. For a relative cutoff use the SQL-side family instead (`qf.epochms_add_day(7)`, `qf.epochms_sub_month(1)`, `qf.epochms_year("UTC")`, …) — or compute it in an earlier `s.set_var` and `ref()` that. `export --strict` reports it; a bare `c.now()` operand is always fine.
1075
1122
  - `bind: [{ table, as?, join?, where? }]` — joins (`context.bind[]`). `join` defaults to `"inner"`. `as` defaults to the table name; two joins to the same table need distinct aliases.
1076
- - ⚠ In `where`/`sort`/`eval` a JOINED column takes a dotted path (`col("team_row.id")`); THIS query's own columns stay **bare** (`col("team")`). Qualifying your own by table name needs `tableAlias` (same rule as `aggregate`) — without it the engine reads the operand as text and 400s `ParseError: Invalid value for param` naming the OTHER operand, so it throws at export instead.
1123
+ - ⚠ In `where`/`sort`/`eval` a JOINED column takes a dotted path (`col("team_row.id")`); THIS query's own columns stay **bare** (`col("team")`). Qualifying your own by table name needs `tableAlias` (same rule as `aggregate`); without it the engine 400s `ParseError: Invalid value for param` naming the OTHER operand, so export throws.
1077
1124
  - `bind: [{ table: team, as: "team_row", join: "left", where: expr(col("team"), "=", col("team_row.id")) }]`
1078
1125
  - `bind: [{ expand: "blog.categories", as: "cat" }]` joins one row per element of a LIST column already in the query; read it as `col("cat.<key>")`.
1079
1126
  - ⚠ A join does NOT put the joined table's columns on the returned row — with or without a `bind`, a row is the QUERIED table's columns, which is what `InferResponse` types. There is no `row.team_row`. To read a joined column, PROJECT it with an `eval` whose `name` is the dotted path: `eval: [{ name: "team_row.name", as: "team_name" }]` puts `team_name` on the row and on the inferred type. A bare `name` there is `Unsupported parameter reference` at runtime (it qualifies to the base table), and a dotted joined column in `output` is dropped with no error.
1080
- - `returnType` — `"list"` (default) | `"single"` | `"count"` | `"exists"` | `"stream"` | `"aggregate"`. Drives `context.return.type` AND the `InferResponse` shape: `count`→`number`, `exists`→`boolean`, `single`→`Row|null`, `stream`→`Row[]` (pageable, no envelope), `list`→`Row[]`/envelope, `aggregate`→rows keyed by the `aggregate.group`/`eval` aliases. ⚠ A bare `count` of ZERO serializes as an EMPTY body, not `0` — a client parsing JSON gets a parse error on the one result it most needs to handle. Wrap it: `response: { count: ref("n") }`.
1081
- - `eval: [{ name, as, filters? }]` — computed columns (`context.eval[]`). Each `as` grafts onto the row as an `unknown` key in `InferResponse`; shadowing a real column throws. Write `name` **bare** (`"embedding"`) — it is alias-qualified on emit exactly like `aggregate` (a bare eval name is `Unsupported param format` at runtime), and the statement declares the alias it used. An `as` alias is `sort`able in the SAME query.
1082
- - An `eval`/`sort`/`where` filter pipeline compiles to **SQL**: `trim`/`lower`/`concat` work there too, plus a DIFFERENT registry than `fl.*`: the vector family, geo `distance`/`within`/`covers`, `search_rank`, the timestamp family, the aggregators. Build these with **`qf.*`** — `filters: [qf.vector_cos_distance(inp("q"))]` — which emits the same `{ name, arg }` step with the name, the argument COUNT and any enumerated argument checked at the call site. `qf` carries what the engine registers, including facts no name list holds: the per-part extractors take a timezone (`qf.epochms_month("UTC")`), `qf.round`'s precision is required, `qf.time`'s part is an enum. `QUERY_FILTER_NAMES`/`QUERY_AGGREGATE_NAMES` list the set; the raw `{ name, arg }` form still works for anything `qf` does not carry (`vector_distance`, which has no registered engine class).
1083
- - **Vector similarity search** — the ONLY way to query an `f.vector` column (no `SearchOp` does distance). `eval: [{ name: "embedding", as: "distance", filters: [{ name: "vector_cos_distance", arg: [inp("q")] }] }]` + `sort: [{ sortBy: "distance", dir: "asc" }]` ranks in the DATABASE over the column's index. Match the filter to the index `op` (`vector_cos_distance`↔`vector_cosine_ops`, `vector_l2_distance`↔`vector_l2_ops`, `vector_l1_distance`↔`vector_l1_ops`, `vector_inner_product`↔`vector_ip_ops`); `vector_cos_similarity` is the inverse, so sort it `desc`. The same filter on a `where` operand cuts off BY distance instead of by row count.
1084
- - `aggregate: { group?, eval?, sort?, paging? }` (with `returnType:"aggregate"`) builds `context.return.aggregate`. `group`/`eval` are `{ name, as, filters? }`, an aggregator like `sum`/`count` riding `filters`. Some aggregators resolve ONLY here, not in a runtime value pipeline: `count_distinct`, `median`, `to_list`/`to_distinct_list` (each with `_asc`/`_desc`), and `vector_distance`.
1085
- - ⚠ Write each `name` as a **bare** column (`"status"`). It is alias-qualified to `"<alias>.status"` on emit — the engine rejects an unqualified column in an aggregate with `Unsupported param format`. An already-dotted `name` (a `bind`ed/joined column) passes through.
1086
- - The alias it qualifies WITH is `tableAlias` when you set one, otherwise the table's name — and the statement DECLARES that alias (`dbo.as`) so the qualified name resolves. Nothing to do by hand; a bare `name` is the form to write.
1127
+ - `returnType` — `"list"` (default) | `"single"` | `"count"` | `"exists"` | `"stream"` | `"aggregate"`. Drives `context.return.type` AND the `InferResponse` shape: `count`→`number`, `exists`→`boolean`, `single`→`Row|null`, `stream`→ a cursor only `s.foreach` reads (returned, it serves `"@stream"`; warns `db.stream-returned`), `list`→`Row[]`/envelope, `aggregate`→rows keyed by the `aggregate.group`/`eval` aliases. ⚠ A bare `count` of ZERO has no reliable shape: it answers `0` or an EMPTY body (a client JSON parse error). Wrap it: `response: { count: ref("n") }`.
1128
+ - `eval: [{ name, as, filters? }]` — computed columns (`context.eval[]`). Each `as` grafts onto the row in `InferResponse` as `unknown`, or as the joined column for an unfiltered `<bind as>.<col>` (`| null` under `left`); shadowing a real column throws. ⚠ `output` is applied to the eval columns too: with a non-empty `output`, LIST the alias there (`output: ["id", "<alias>"]`) or the engine drops it from the result (`export()` warns `db.eval-unselected`; an ADDON alias survives an omitting `output`, an eval alias does not). Write `name` **bare** (`"embedding"`) — it is alias-qualified on emit exactly like `aggregate` (a bare eval name is `Unsupported param format` at runtime), and the statement declares the alias it used. An `as` alias is `sort`able in the SAME query. ⚠ An eval over a LIST column (`f.text({ array: true })`) is PER-ELEMENT (the engine unnests the column), so its `filters` must START with an AGGREGATE (`qf.count()` for the element count, `qf.to_list()`, …): a non-aggregate first filter like `qf.array_length()` 500s `Aggregate filter must be processed first` at request time, with no export warning.
1129
+ - An `eval`/`sort`/`where` filter pipeline compiles to **SQL**: `trim`/`lower`/`concat` work there too, plus a DIFFERENT registry than `fl.*`: the vector family, geo `distance`/`within`/`covers`, `search_rank`, the timestamp family, the aggregators. Build these with **`qf.*`** — `filters: [qf.vector_cos_distance(inp("q"))]` — which emits the same `{ name, arg }` step with the name, the argument COUNT and any enumerated argument checked at the call site. `qf` carries what the engine registers: the per-part extractors take a timezone (`qf.epochms_month("UTC")`), `qf.round`'s precision is required, `qf.time`'s part is an enum. `QUERY_FILTER_NAMES`/`QUERY_AGGREGATE_NAMES` list the set; the raw `{ name, arg }` form still works for anything `qf` does not carry (`vector_distance`, which has no registered engine class).
1130
+ - **Vector similarity search** — the ONLY way to query an `f.vector` column (no `SearchOp` does distance). `eval: [{ name: "embedding", as: "distance", filters: [qf.vector_cos_distance(inp("q"))] }]` + `sort: [{ sortBy: "distance", dir: "asc" }]` ranks in the DATABASE over the column's index. Match the filter to the index `op` (`vector_cos_distance`↔`vector_cosine_ops`, `vector_l2_distance`↔`vector_l2_ops`, `vector_l1_distance`↔`vector_l1_ops`, `vector_inner_product`↔`vector_ip_ops`); `vector_cos_similarity` is the inverse, so sort it `desc`. The same filter on a `where` operand cuts off BY distance instead of by row count.
1131
+ - **Full-text search** — query a `type: "search"` index by the `name` you gave it, spelled as a column `"$<name>"`: `where: cmp(col("$ft"), "search", inp("q"))`, rank with `eval: [{ name: "$ft", as: "rank", filters: [qf.search_rank(inp("q"))] }]` + `sort: [{ sortBy: "rank", dir: "desc" }]` (the field `priority` weights the rank). ⚠ A `"search"` cmp on a PLAIN column (`col("title")`, no `$`) 500s, and an UNNAMED search index can't be referenced at all (warns `table.search-index-unnamed`).
1132
+ - `aggregate: { group?, eval?, sort?, paging? }` (with `returnType:"aggregate"`) builds `context.return.aggregate`. `group`/`eval` are `{ name, as, filters? }`, an aggregator like `sum`/`count` riding `filters`. Some aggregators resolve ONLY here, not in a runtime value pipeline: `count_distinct`, `median`, `to_list`/`to_distinct_list` (each with `_asc`/`_desc`), and `vector_distance`. ⚠ `avg` over a group whose values are ALL null returns `0`, not `null` (an unrated item reads as rated zero); a group with SOME nulls correctly averages only the non-nulls.
1133
+ - ⚠ Write each `name` as a **bare** column (`"status"`). It is alias-qualified to `"<alias>.status"` on emit — the engine rejects an unqualified column in an aggregate with `Unsupported param format`. ⚠ A JOINED column cannot be named here (refused at build): project it with a query `eval` (`{ name: "pr.name", as: "pname" }`) and name that alias BARE (`group: [{ name: "pname", as: "pname" }]`).
1134
+ - It qualifies with `tableAlias`, else the table's name, and the statement declares that alias (`context.dbo.as`) itself.
1087
1135
  - `sort: [{ sortBy: <col>, dir?: "asc"|"desc"|"rand" }]` and `paging: { page?, per_page?, offset?, totals?, metadata?, search?, sort? }` ride `context.return.list`.
1088
1136
  - ⚠ `paging` with a page/per_page/offset field and `metadata` on (the DEFAULT) wraps the result in an envelope `{ items: Row[], curPage, nextPage, prevPage, offset, perPage, itemsReceived }` — plus `itemsTotal`/`pageTotal` when `totals: true` — instead of a bare `Row[]`. `InferResponse` reflects it. `paging: { metadata: false }` keeps the bare array.
1089
1137
  - ⚠ Under the ENVELOPE, `output` selects from the envelope, not the row: write `output: ["itemsReceived", "curPage", "items.id", "items.title"]`. A bare column list matches no envelope key, so every key is dropped and the response is `[]` at HTTP 200 with no error (and `ref("<var>.items")` then fails on a var that is gone). With `metadata: false` the statement binds the rows, so bare columns are the right form there. `export()` warns on a row-rooted selection under an envelope; `--strict` fails it.
1090
1138
  - Read `nextPage` (`number|null`) as the typed has-next signal.
1091
1139
  - **Input-bound paging:** `page`/`per_page`/`offset` also accept a `Value` (`inp("page")`), riding `context.simpleExternal` while the static block stays the engine gate (`enabled:true`). `paging.search`/`sort` are `Value` dynamic overrides.
1092
1140
  - A `search`/`sort`-only `paging` (no numeric field) does NOT paginate.
1093
- - `external: { value, permissions? }` — the classic whole-config blob (forces the gate on). It falls back to input-bound `paging` when it resolves empty, so supplying both is valid.
1141
+ - `external: { value, permissions? }` — the whole paging config as one value (forces the gate on). It falls back to input-bound `paging` when it resolves empty, so supplying both is valid.
1094
1142
  - `distinct` — `"auto"` (default) | `"yes"` | `"no"`, riding `context.return.<list|stream>.distinct`.
1095
1143
  - `s.db.truncate({ table, reset?, as? })` · `s.db.schema({ table, path, as? })`.
1096
1144
  - `s.db.direct_query({ sql, responseType?, args?, parser?, as? })` — `sql` is a **raw string** (not a `Value`); binds go in `args: Value[]`. `parser: "template_engine"` renders the body as a template first — how a query interpolates a column or table name a bound arg cannot carry; omit it for the default.
1097
1145
  - Template placeholders are Twig over the request scope: `{{ $input.name }}` for an input, `{{ $var.name }}` for a stack variable. ⚠ A BARE `{{ name }}` renders as the empty string — HTTP 200, no error, a query that silently ran with a blank where the value belonged. A bound `?` arg carries a VALUE without the template at all.
1098
- - ⚠ A table's PHYSICAL name is **not stable across deploys**. A deploy is a full replace, so every table is created afresh and the id in its name moves every time — the same unchanged project redeployed three times gave one table three different names. Never store, cache, hardcode or fixture one: resolve it from `information_schema` inside the same request that uses it.
1099
- - `s.db.external.<engine>.direct_query({ sql, connectionString, responseType?, args?, parser?, as? })` — same shape against an EXTERNAL database; `<engine>` is `postgres`/`mysql`/`mssql`/`oracle`/`snowflake`. `connectionString` is a `Value` — reach for `env(...)`, not a literal — stored as `context.connection_string_flex`. A bare string stores the older `context.connection_string` instead (an env-var name unless it looks like a URL); each form round-trips as itself.
1100
- - `s.db.transaction({ body })` — run a `Statement[]` atomically. It returns nothing, so it takes no `as`: read what the body binds. An `s.return` in the body ends the WHOLE stack with that value, and the writes before it commit.
1146
+ - ⚠ A table's PHYSICAL name is **not stable across deploys**. A deploy is a full replace that recreates every table, so the id in its name changes on every deploy. Never store, cache, hardcode or fixture one: resolve it from `information_schema` inside the same request that uses it.
1147
+ - `s.db.external.<engine>.direct_query({ sql, connectionString, responseType?, args?, parser?, as? })` — same shape against an EXTERNAL database; `<engine>` is `postgres`/`mysql`/`mssql`/`oracle`/`snowflake`. `connectionString` is a `Value` — reach for `env(...)`, not a literal — stored as `context.connection_string_flex`. A bare string stores `context.connection_string` instead (an env-var name unless it looks like a URL); each form round-trips as itself.
1148
+ - `s.db.transaction({ body })` — run a `Statement[]` atomically. It returns nothing, so it takes no `as`: read what the body binds. An `s.return` in the body ends the WHOLE stack with that value, and the writes before it commit. ⚠ Atomic, not exclusive: a check-then-insert DOUBLE-BOOKS under concurrency (`lock: true` on the check locks only rows it returns). First lock a shared PARENT row: `s.db.get({ table: rooms, fieldValue: inp("room_id"), lock: true, as: "room" })`.
1101
1149
  - The body shares the enclosing stack: a variable it binds (`as: "order"` on an `s.db.add`) is still bound AFTER the transaction.
1102
1150
  - `s.db.bulk.add({ table, items, allowIdField?, as? })` / `s.db.bulk.update` / `s.db.bulk.patch` — `items` is an array `Value`.
1103
- - ⚠ `bulk.add` **drops `id` on every row unless `allowIdField: true`** (silently, next sequence value instead) — the opposite of `seed`, where `id` pins. Rows referenced by a foreign key need `allowIdField: true`; literal `items` carrying `id` without it throw. `bulk.update`/`patch` keep `id` (their match key).
1104
- - ⚠ **`bulk.update` is a whole-row REPLACE: every column an item OMITS is zeroed** (`""`/`0`/`null`), HTTP 200, no error — `{ id: 7, status: "done" }` blanks the rest of row 7. **Use `s.db.bulk.patch`** for the partial write "update these rows" means. `export()` warns on a STATIC `items` missing columns (`--strict` fails); a `ref`/`inp` `items` is uninspectable.
1105
- - `s.db.bulk.delete({ table, where?, allRows?, as? })` — deletes rows by a `context.search` filter. `where` is the same surface as `s.db.query` (`expr(...)`/`cmp(...)`, `and(...)`/`or(...)` groups, an array of those ANDed, or a raw `Value`) and encodes through the identical `{expression:[…]}` search shape. ⚠ A filter that constrains nothing (missing, empty, or `x OR and()`) deletes **every** row, so it **throws**: pass the filter, or `allRows: true` for a deliberate wipe (both together also throw). `allRows` emits the empty search the engine requires and returns the deleted count; reach for `s.db.truncate({ table, reset: true })` when the id sequence should restart too.
1106
- - `s.db.increment({ table, where, fieldName, value, returnType?, output?, addon?, as? })` — adds `value` (a number or `Value`; negative decrements) to one `int`/`decimal` column on every row `where` matches, in ONE atomic locked UPDATE. **Use it for counters, stock, balances and tallies**: `db.get` → math → `db.edit` loses updates under concurrency, and so do `db.bulk.patch`/`update`. A guard in `where` (`expr(col("stock"), ">=", c.int(1))`) is re-checked under the row lock. `returnType: "count"` binds the changed-row count instead of the rows, and then takes no `output`/`addon`.
1151
+ - ⚠ `bulk.add` **drops `id` on every row unless `allowIdField: true`** (silently, next sequence value instead) — the opposite of `seed`, where `id` pins. Rows referenced by a foreign key need `allowIdField: true`; literal `items` carrying `id` without it throw. `bulk.update`/`patch` keep `id` (their match key). A unique violation rolls back the WHOLE batch: 500 "SQL Error: 23505, UNIQUE VIOLATION".
1152
+ - ⚠ **`bulk.update` is a whole-row REPLACE: every column an item OMITS is zeroed** (`""`/`0`/`null`), HTTP 200, no error — `{ id: 7, status: "done" }` blanks the rest of row 7. It also resets `created_at`. **Use `s.db.bulk.patch`** for the partial write "update these rows" means. `export()` warns on a STATIC `items` missing columns (`--strict` fails); a `ref`/`inp` `items` is uninspectable.
1153
+ - `s.db.bulk.delete({ table, where?, allRows?, as? })` — deletes rows by a `context.search` filter. `where` is the same surface as `s.db.query` (`expr(...)`/`cmp(...)`, `and(...)`/`or(...)` groups, an array of those ANDed) and encodes through the identical `{expression:[…]}` search shape. ⚠ A filter that constrains nothing (missing, empty, or `x OR and()`) deletes **every** row, so it **throws**: pass the filter, or `allRows: true` for a deliberate wipe (both together also throw). `allRows` emits the empty search the engine requires and returns the deleted count; reach for `s.db.truncate({ table, reset: true })` when the id sequence should restart too.
1154
+ - `s.db.increment({ table, where, fieldName, value, returnType?, output?, addon?, as? })` — adds `value` (a number or `Value`; negative decrements) to one `int`/`decimal` column on every row `where` matches, in ONE atomic locked UPDATE. **Use it for counters, stock, balances and tallies**: `db.get` → math → `db.edit` loses updates under concurrency, and so do `db.bulk.patch`/`update`. A guard in `where` (`expr(col("stock"), ">=", c.int(1))`) is re-checked under the row lock. To guard one column against ANOTHER of the same row (`used < max_uses`), set `tableAlias` on the statement and qualify the RIGHT operand with it (`expr(col("used"), "<", col("cpn.max_uses"))` with `tableAlias: "cpn"`) (a bare right-hand column throws at export). `returnType: "count"` binds the changed-row count instead of the rows, and then takes no `output`/`addon`.
1107
1155
  - ⚠ A `where` that constrains nothing (missing, empty, or `x OR and()`) changes NO rows and **throws**. A null stored value counts as 0. A fractional `value` on an `int` column, a non-numeric or list column, the `id` key, and a result that overflows the column are rejected with no rows changed.
1108
1156
 
1109
1157
  # Statement runtime behavior
@@ -1112,9 +1160,11 @@ primary key `id`):
1112
1160
 
1113
1161
  Runtime behavior (what the `as:` output holds, and misses):
1114
1162
 
1115
- - `db.get` binds **`null`** when no row matches (it does NOT throw) — so the output is `InferRow<typeof table> | null`; null-check it. On a hit it binds the **full row**. (`db.has` is the boolean existence test.)
1116
- - `db.edit` binds the **full, post-mutation row**. `db.add` binds the **full inserted row**, including the auto-assigned `id` and `created_at`. So `InferRow<typeof table>` is the right response type for those two. `db.del` **binds `null`**, not the deleted row.
1117
- - Unlike `db.get`, `db.edit` and `db.del` **throw** `NotFound` (HTTP 404) when no row matches the field. `db.add` throws on a unique-constraint violation: HTTP 500 `ERROR_FATAL` "Duplicate record detected…", earlier writes kept. No error type is 409. `s.try_catch` catches it — and `s.precondition`/`guard.*` failures, answering 200 (`caught("code")`: `ERROR_CODE_NOT_FOUND`, …) — so re-raise with an `s.precondition` in `catch` to keep a status. No partial unique index: NULLs never collide, so null the key (or delete the row) to free it.
1163
+ - `db.get` binds **`null`** when no row matches (it does NOT throw); null-check it. On a hit it binds the **full row**. (`db.has` is the boolean existence test.)
1164
+ - `db.edit` binds the **full, post-mutation row**. `db.add` binds the **full inserted row**, including the auto-assigned `id` and `created_at`. `db.del` **binds `null`**, not the deleted row.
1165
+ - Unlike `db.get`, `db.edit` and `db.del` **throw** `NotFound` (HTTP 404) when no row matches the field. `db.add` throws on a unique-constraint violation: HTTP 500 `ERROR_FATAL` "Duplicate record detected…", earlier writes kept. No error type is 409.
1166
+ - `s.try_catch` catches it — and `s.precondition`/`guard.*` failures, answering 200 (`caught("code")`: `ERROR_CODE_NOT_FOUND`, …) — so re-raise with an `s.precondition` in `catch` to keep a status.
1167
+ - No partial unique index: NULLs never collide, so null the key (or delete the row) to free it. ⚠ A unique-index column that may be ABSENT must be `nullable: true` — a NON-nullable column stores an omitted/null cell as its zero value (`""`/`0`), which is NOT null and DOES collide, so only ONE row can omit it (the second 500s `Duplicate record detected`). An "optional composite key" needs the columns `nullable: true`.
1118
1168
  - **`InferResponse<typeof query>`** derives an endpoint's response type. It resolves object-literal responses to those keys; a `response: ref("x")` returning a variable bound by a TOP-LEVEL db op on a `table()` resolves to that op's result:
1119
1169
  | statement | resolves to | on a miss |
1120
1170
  |---|---|---|
@@ -1124,42 +1174,50 @@ Runtime behavior (what the `as:` output holds, and misses):
1124
1174
  | `db.has` | `boolean` | — |
1125
1175
  | `db.bulk.delete` | `number` (count) | — |
1126
1176
  | `db.increment` | `Row[]` (updated rows), or `number` with `returnType: "count"` | `[]` / `0` |
1127
- | `db.del`, `db.bulk.add`/`bulk.update`, raw `direct_query` | `unknown` (the engine leaves them untyped) | — |
1128
- - A `get`/`query` `output: [...]` selection narrows to a `Pick` (still `| null` for `get`). A dotted `ref("row.col")` into a `db.get` row projects that column carrying the `| null` (→ `Col | null`).
1177
+ | `db.del`, `db.bulk.add`/`bulk.update`, raw `direct_query` | `unknown` (untyped; `bulk.add` binds the new ids, `bulk.update` the rows) | — |
1178
+ - A `get`/`query` `output: [...]` selection narrows to a `Pick` (still `| null` for `get`). A dotted `ref("row.col")` into a `db.get` row types `Col` (a miss 500s); `ref(path, { safe: true })` types `Col | null`.
1129
1179
  - A value reshaped by a lambda, or a variable built by control flow, also resolves to `unknown`.
1130
1180
  - A CALL binds the TARGET's response type: `s.function.call`/`s.function.run`/`s.api.call`/`s.tool.call` given a def HANDLE brand their `as` with `InferResponse` of the target, so `ref("out.field")` types to that field. What the target resolves to is what propagates — declare `responseShape` on the TARGET to fix every caller at once. A target named by STRING has no def to read and stays `unknown`; an async `s.function.run` binds its job id (`string`), not the result.
1131
1181
  - In an object-literal response the KEYS are always known; a `c.*` constant VALUE types like an `s.set_var` of it (`{ success: c.bool(true) }` → `{ success: boolean }`).
1132
- - A NESTED member resolves to any depth by these same rules, in either spelling — `{ user: obj({ id: ref("row.id") }) }` and the raw literal `{ user: { id: ref("row.id") } }` both derive `{ user: { id: Col | null } }`. A raw scalar member types itself (`{ count: 3 }` → `number`).
1182
+ - A NESTED member resolves to any depth, in either spelling — `{ user: obj({ id: ref("row.id") }) }` and the raw literal `{ user: { id: ref("row.id") } }` both derive `{ user: { id: Col } }`. A raw scalar NESTED member types itself (`{ stats: { count: 3 } }` → `{ stats: { count: number } }`), but a TOP-LEVEL member must be a `Value` — a bare scalar there (`{ count: 3 }`) is a type error and `query()` throws at load, so write `{ count: c.int(3) }`.
1133
1183
  - Runs on every response-bearing kind — `query`, `defineFunction`, `realtimeMessage`, `tool`, `middleware`, and the response-bearing triggers — each of which also accepts `responseShape`. A trigger builds its stack and response through CALLBACKS (`stack: (t) => [...]`), and the trace follows through them.
1134
- - Close any `unknown` by declaring `responseShape` on the def (`responseShape: null as InferRow<typeof t> | null`) — the declaration ALWAYS overrides derivation. It is available on EVERY kind listed above, `query` included.
1135
- - The shapes that never derive, and the one line that closes each: rows built in `s.lambda` (JS is opaque to the walk) → `responseShape: [] as Row[]`; a var bound ONLY inside branches → `responseShape` (a branch/case/loop/`try`/`catch` re-binding unions in; one in EVERY branch replaces); a call whose target is named by STRING → give the TARGET a `responseShape` (a handle then carries it) or declare it here. Use `responseShape` as the FIRST move here.
1184
+ - The FIRST move for any `unknown`: declare `responseShape` on the def (`responseShape: null as InferRow<typeof t> | null`) — available on EVERY kind listed above, `query` included; the declaration ALWAYS overrides derivation. The shapes that never derive, and the one line that closes each: rows built in `s.lambda` (JS is opaque to the walk) → `responseShape: [] as Row[]`; a var bound ONLY inside branches → `responseShape` (a branch/case/loop/`try`/`catch` re-binding unions in; one in EVERY branch replaces); a call whose target is named by STRING → give the TARGET a `responseShape` (a handle then carries it) or declare it here.
1136
1185
  - An `s.set_var` holding a `c.*` CONSTANT brands its binding with that constant's JS type, so `ref("n")` after `s.set_var("n", c.int(1))` resolves to `number` (widened: `c.bool(false)` → `boolean`; `s.update_var` re-binds). A filter chain — the value's own or `asFilters` — then retypes it (`[fl.to_int()]` → `number`). A bare `ref`/`inp` stays `unknown`.
1137
- - ⚠ A hand-written `s.precondition` does not narrow the STATIC type. One (or a conditional) proving a `db.get` row non-null leaves `InferResponse` at `Row | null`, because the walk reads the stack's shape and not its control flow. `guard.found("row")` DOES narrow: it emits the same non-null check (404) and drops `| null` from `row` — whole, dotted, and addon grafts alike — after it. `guard.owner` narrows the same way. Reach for `responseShape` only when neither fits.
1186
+ - ⚠ A var bound ONLY inside a branch body — an `s.conditional` `then`/`else`/`elif`, an `s.switch` case, a loop body (`s.for`/`s.foreach`) that ran zero times, or an `s.try_catch` `try` — does NOT exist when that path is skipped, so a later `ref` to it 500s `Missing var entry: <name>` (NOT null). `{ safe: true }` does NOT suppress it (it has no effect on a bare, dot-free name), and export warns `stack.var-conditionally-bound`. Declare the var on the ENCLOSING path first: `s.set_var("x", c.null())` before the block.
1187
+ - ⚠ A hand-written `s.precondition` does not narrow the STATIC type. One (or a conditional) proving a `db.get` row non-null leaves `InferResponse` at `Row | null`. `guard.found("row")` DOES narrow: it emits the same non-null check (404) and drops `| null` from `row` — whole, dotted, and addon grafts alike — after it. `guard.owner` narrows the same way. Reach for `responseShape` only when neither fits.
1188
+ - ⚠ `InferResponse` reads the `response` field ALONE — an `s.return(value)` ANYWHERE in the stack (an early cache hit, an idempotent replay, a `respond.status(409)` + `s.return` fast path) is INVISIBLE to it, including ones nested in `s.conditional`/`switch`/`foreach`/`try`. So the type covers only the fall-through `response`, and a typed client misses every early body. Declare `responseShape` as the UNION of every body the endpoint can serve: `responseShape: null as { value: number } | { cached: boolean }` (without one, export warns `response.return-outside-type`).
1138
1189
  - ⚠ A `resultStrategy: "replace"` middleware attached `post` reshapes the endpoint's output at runtime, which the static walk cannot see. Declare `responseShape` when a post middleware rewrites the response. A `merge` one makes a LIST response an index-keyed object; its keys are not inferred.
1139
- - ⚠ **Spreading a `Statement[]` helper into a stack kills the whole walk.** The trace needs the stack's TUPLE type, so `...myHelper()` where the helper returns `Statement[]` widens it and EVERY `as` in that stack — including ones declared after the spread — stops resolving. The response then types as `StackTupleWidened`, whose name says so. Fix: return `statements(s.a(...), s.b(...))` from the helper (a const-generic identity export — the tuple survives the spread). A helper that builds its array in a LOOP cannot be a tuple; declare `responseShape` there.
1190
+ - ⚠ **Spreading a `Statement[]` helper into a stack kills the whole walk.** `...myHelper()` where the helper returns `Statement[]` widens the stack's TUPLE type, and EVERY `as` in that stack — including ones declared after the spread — stops resolving. The response then types as `StackTupleWidened`. Fix: return `statements(s.a(...), s.b(...))` from the helper (preserves the tuple). A helper that builds its array in a LOOP cannot be a tuple; declare `responseShape` there.
1140
1191
  - **Addons** enrich returned rows. `db.query`/`get`/`add`/`edit`/`patch` accept `addon: [{ addon, as, input?, output?, children? }]`; `db.add_or_edit`/`del`/`has`/`truncate` take no `addon`.
1141
1192
  - `addon` is the target (name or def handle). `as` is the destination on the row — a bare alias (`"_user"`) or a dotted `offset.alias`, authored relative to a row. Under a metadata paging envelope the `items[]` offset is prefixed automatically; writing it yourself is tolerated and not double-prefixed.
1142
1193
  - `envelope: true` grafts once onto a paged query's envelope instead of each row.
1143
- - `input` maps addon inputs — bind a parent-row column with `out(col)`. `output` restricts addon columns. `children` nests addons.
1194
+ - `input` maps addon inputs — bind a parent-row column with `out(col)`. `output` restricts addon columns. `children` nests addons onto each graft element (typed).
1144
1195
  - The DEFINITION side — the `addon({...})` factory and `registerAddons` — is a def shape in `llms/kinds-core.md`.
1145
- - Attaching a typed `addon({ table, output })` handle merges its alias (the last `as` segment) onto the row in `InferResponse`: `{cols} | null` for `single`, `{cols}[]` for `list`, `number` for `count`, `boolean` for `exists`, and for `aggregate` an array keyed by the `group`/`eval` aliases (`unknown` values; `unknown` when neither is declared).
1196
+ - Attaching a typed `addon({ table, output })` handle merges its alias (the last `as` segment) onto the row in `InferResponse`: an OPTIONAL `{cols}` for `single` (absent, not null, on no match), `{cols}[]` for `list`, `number` for `count`, `boolean` for `exists`, and for `aggregate` an array keyed by the `group`/`eval` aliases — ONE optional object when `eval` has no `group` (`unknown` values; `unknown` when neither is declared).
1146
1197
  - An attachment-level `output` narrows an object/array graft further. A bare-NAME reference grafts `unknown` — narrow it at the call site.
1147
1198
  - ⚠ An alias that shadows an existing column on the queried table throws at build time; rename with a `_` prefix.
1148
1199
  - **Middleware attachment** runs a reusable `middleware({...})` before/after a host's own stack. Distinct from `s.middleware.call` (inline invoke).
1149
1200
  - Attach with the host's `middleware: { pre, post }` field on `query`/`function`/`task`/`tool`/`apiGroup` (NOT triggers): each phase is an ordered list of middleware refs (def handle or name), or `{ middleware, active: false }` to keep an entry disabled.
1150
1201
  - Providing a phase **overrides** it (sets the stored `pre_customize`/`post_customize` flag); omitting a phase **inherits** the parent tier's chain — the engine resolves Query → API Group → Workspace at request time (override, not merge; the API-Group tier applies to queries — functions/tasks/tools have no API-group binding and inherit straight from the workspace).
1151
1202
  - Prefer a def handle over a bare name when the middleware pins an explicit `guid`.
1203
+ - `exceptionPolicy` governs what a **throw** in the middleware stack does to the request. `"rethrow"` is the **default** — the throw aborts the request and surfaces the authored `error`/status (a tripped `s.redis.ratelimit` → HTTP 429); the `post` chain still runs. `"silent"` swallows the throw, so a guard set to it is **not enforced** — advisory middleware only. `"critical"` is `"rethrow"` plus skipping the `post` chain.
1152
1204
  - `pre: middleware.clear()` (an empty list) overrides with nothing — stop inheriting.
1153
1205
  - Workspace-level defaults are the terminal tier: `workspaceConfig({ middleware: { query: { pre }, function, task, tool } })` emits the flat `{host}_{phase}` map (no `_customize` flags) — setting it replaces the whole workspace map, so unlisted hosts are cleared; omit the field to leave existing workspace middleware untouched.
1154
1206
  - **Middleware request context.** A `pre` middleware runs **after** auth resolution, so `auth()` is available inside the middleware when the host is authenticated (its `auth` names an auth table); on a public host there is no caller identity for it to resolve.
1155
- - This matters for the canonical use — a rate limit keyed by `auth("id")`: on an authenticated endpoint the bucket is per-user, but attach the same middleware to a public endpoint and `auth()` cannot resolve, so the request FAILS with a 403 on the first call, under `max`, with the host never running. Key off `sys.remoteIp()` on a public host.
1156
- - To catch that, `export()` **warns** (never blocks) when a middleware whose stack references `auth()` reaches a host where `auth()` may be null — a `query` with no auth table, a `task` (scheduled, never authenticated), or a `function`/`tool` (whose auth is caller-dependent). An authenticated query (its own `auth` table set) is skipped.
1207
+ - A rate limit keyed by `auth("id")` is per-user on an authenticated endpoint; on a public endpoint `auth()` cannot resolve, so the request FAILS with a 403 on the first call, under `max`, with the host never running.
1208
+ - `export()` **warns** (never blocks) when a middleware whose stack references `auth()` reaches a host where `auth()` may be null — a `query` with no auth table, a `task` (scheduled, never authenticated), or a `function`/`tool` (whose auth is caller-dependent). An authenticated query (its own `auth` table set) is skipped.
1157
1209
  - Inherited attachment (API group, workspace tier) warns too.
1158
1210
  - **Rate-limit recipe (the canonical middleware).** Author it with `s.redis.ratelimit` and a **composite key** built via the filter chain — `"prefix" + auth("id")` does not exist, you build the key: `middleware({ name: "write_rl", exceptionPolicy: "rethrow", stack: [ s.redis.ratelimit({ key: withFilters(c.text("rl:write:"), fl.concat(auth("id"))), max: c.int(10), ttl: c.int(30), error: c.text("Too fast.") }) ] })`.
1159
- - `exceptionPolicy` defaults to `"rethrow"`, which is what makes a tripped limit abort with HTTP 429; `"silent"` would let the over-limit request through. Without `error` it never trips: it binds `false` and the request runs on (`export()` warns).
1211
+ - The default `exceptionPolicy: "rethrow"` aborts a tripped limit with HTTP 429; `"silent"` lets the over-limit request through. Without `error` it never aborts — the request always runs on (`export()` warns) — but the bound value is NOT constant `false`: it binds `true` while the caller is under `max` and `false` once over (branch on it with that polarity).
1160
1212
  - Attach it with `middleware: { pre: [writeRl] }` on an **authenticated** host; on a public host key off `sys.remoteIp()`.
1161
1213
  - **Shared-bucket rule:** co-attaching one middleware object to N hosts means all N share the *same* key ⇒ *one* counter — `max: 10` is a global per-user budget across them, not 10-per-host. Vary the key (fold in the host/action name) for an independent limit per host.
1162
- - **Middleware `exceptionPolicy`** governs what a **throw** in the middleware stack does to the request. `"rethrow"` is the **default** — the throw aborts the request and surfaces the authored `error`/status (a tripped `s.redis.ratelimit` → HTTP 429); the `post` chain still runs. `"silent"` swallows the throw, so a guard set to it is **not enforced** — advisory middleware only. `"critical"` is `"rethrow"` plus skipping the `post` chain.
1214
+ - **Redis (`s.redis.*`) semantics.** ⚠ `set` REFUSES a null or `""` `data` with HTTP 400 `Missing param: data`, so you cannot negative-cache an empty/absent result — store a sentinel (`c.text("__none__")`) instead. A stored `false` reads back from `get` as `false`, INDISTINGUISHABLE from a miss — use `has` to tell them apart. `ttl: 0` means FOREVER (no expiry); a NEGATIVE `ttl` is a 500 `Unable to store data in cache`. `incr`/`decr` on a missing key start at 0 and bind the new value (a negative `by` works). List ops: `push`/`unshift` bind the new LENGTH; `pop`/`shift` bind one element, or a list with `count` (last-first, `pop count 2` → `[5,4]`); on an empty or missing key they bind `false` (not null); `count` on a missing key is `0`, `range` is `[]` (and `range` with no start/stop is the whole list); `remove` with no `count` drops EVERY occurrence, with `count` it binds the number removed. `keys({ search })` is a GLOB binding the full key names. Objects and lists round-trip through `set`/`get` and the list ops.
1215
+ - **File resources** — the value the `s.storage.*` and `s.zip.*` statements pass BETWEEN each other. A file resource is a short-lived (~24 h) TOKEN, not storage. PRODUCED by `inp("file")` (an `input.file`), `s.storage.create_file_resource`, `s.zip.create_archive`, and an extract entry's `.resource`. CONSUMED by `s.storage.read_file_resource`, the `s.storage.create_*` statements, and `s.zip.add_to_archive`/`view_contents`/`extract`. ⚠ A STORED file is NOT one: a `f.attachment()` cell / a `create_attachment` result / a cell's `url` passed to `read_file_resource` or `s.zip.*` 500s `Invalid file resource` — a stored file's bytes are not readable back through these. ⚠ `s.zip.extract` binds `[{ name, size, last_modified, resource }]`; pass the entry's `.resource` (`ref("extracted.0.resource")`) to `read_file_resource`, NOT the entry itself (500). ⚠ In a RESPONSE a file resource serializes as an opaque token STRING, not an object, and it EXPIRES — persisting one in a table/redis looks fine and breaks later. `read_file_resource` binds `{ name, size, mime, data }` where `data` is RAW bytes — `fl.base64_encode()` it in the stack before a JSON response (which mangles raw binary). `create_file_resource` refuses a `/` in `filename` (400 `Invalid characters detected.`), though a `zip.add_to_archive` ENTRY name accepts `dir/b.txt`.
1216
+ - **Zip archives (`s.zip.*`)** — build then PERSIST. `s.zip.create_archive({ filename, password?, password_encryption?, as: "zip" })` binds an archive handle; `s.zip.add_to_archive`/`delete_from_archive` bind NOTHING and MUTATE the var passed as `zip` IN PLACE (loop over files, `create_file_resource` each, then `add_to_archive({ file: ref("res"), filename, zip: ref("zip") })`). ⚠ `view_contents`/`extract` on an archive with NO entries 500s (`Invalid or uninitialized Zip object` / `Fatal Error`) — guard a possibly-empty export with a count check. `view_contents` binds `[{ name, size, last_modified }]`, `extract` `[{ name, size, last_modified, resource }]` (the `.resource` is a file resource; see **File resources**). PERSIST the archive with `s.storage.create_attachment({ value: ref("zip") })` (a bare file resource in a response expires). `password` with no `password_encryption` writes standard ZipCrypto; `AES-256` writes method 99, which macOS `unzip` cannot read; the password is per-entry and checked on extract. `delete_from_archive` of a name not in the archive is a silent no-op. ⚠ `create_archive` needs a PAID (non-free) instance. (Uploaded archives must arrive as Content-Type `application/zip` — see `llms/errors.md`.)
1217
+ - **`s.math.*` MUTATES a variable in place** — `s.math.add`/`sub`/`mul`/`div`/`mod`/`bitwise.*` take `{ name, value }` and REWRITE the existing var `name` (declare it with `s.set_var` first; an undeclared `name` 500s `Missing var entry`). There is NO `as` — the catalog's `[output]` on `add`/`bitwise.*` is an engine artifact, the result is the mutated var. Numeric TEXT coerces (`"5" + 3` → `8`) and a null var acts as `0`; a non-numeric operand (`true`, `"abc"`, a list) 500s `Numbers are required for mathematical operations`. `div` of int/int yields a DECIMAL unless it divides exactly (`7/2` → `3.5`, `6/3` → `2`); `div`/`mod` by `0` is a catchable `ERROR_FATAL` (`Division by zero`/`Modulo by zero`). Integer overflow past signed-64-bit SILENTLY becomes a float (`9223372036854775807 + 1` → `9.22e18`), losing exactness; `bitwise.*` truncate a decimal operand and use two's complement on negatives. Same rules on the `fl.*` equivalents.
1218
+ - **`s.math.mod` / `fl.mod` is INTEGER modulo** — unlike its siblings `add`/`sub`/`mul`/`div`, which handle decimals exactly, `mod` TRUNCATES both operands toward zero before the remainder, so a decimal modulo returns WRONG data at HTTP 200: `c.decimal(5.5) mod c.decimal(2.5)` → `1` (the true remainder is `0.5`), and the sign follows the dividend (`-7 mod 3 = -1`). A divisor with `|x| < 1` truncates to 0 and 500s `Modulo by zero`. `c.expression("5.5 % 2.5")` and `withFilters(…, fl.mod(2.5))` do the same (engine-wide PHP `%`). For a REAL decimal remainder compute `a - b*floor(a/b)` with the decimal `div`/`mul`/`sub`, or a lambda.
1219
+ - **Math failure modes** (`fl.*` aggregates and arithmetic, same engine as `s.math.*`). ⚠ On an EMPTY list the aggregates DISAGREE: `fl.sum` → `0`, `fl.product` → `1`, `fl.min`/`fl.max` → `null`, but `fl.avg` 500s `Infinite value` (an `avg` over a filtered list that comes back empty fails the whole request) — guard it with `fl.count()` or a conditional. `fl.ln(0)` raises a catchable `ERROR_FATAL` `Infinite value`. ⚠ A NaN or ±INF result does NOT raise: `fl.sqrt`/`fl.ln`/`fl.log`/`fl.log10` of a NEGATIVE, `fl.pow` of a negative base to a fractional power or past the float range, `fl.acos`/`fl.asin` outside [-1, 1], `fl.acosh` below 1, `fl.atanh` at or beyond ±1. A response carrying one serializes to nothing and answers HTTP 200 with an EMPTY body (a JSON client throws on parse, far from the cause), so guard the operand's domain with an `s.conditional` BEFORE the filter. `fl.number_format` on a text value 500s.
1220
+ - **Date filter failure modes** — the request-time date filters fail QUIETLY on null/empty/unparseable input. A NULL or omitted timestamp reads as epoch 0, so `fl.epochms_date` formats it as `1970-01-01 …` and `fl.epochms_transform` shifts from 1970 — GUARD a nullable timestamp (`s.conditional` on `= null`) before formatting. `fl.epochms_from_format` returns `""` on a parse MISS (treat `""` as failure) and a numeric STRING (not an int) on a hit. `fl.to_epochms` binds `0` for `""` but 400s `Invalid timestamp format.` on non-empty garbage (the one that fails the request, not silently). `fl.epochms_transform` quirks: `llms/filters.md`.
1163
1221
 
1164
1222
  - **Request history** controls per-object execution capture (the request/task/trigger debugger). Authored as a single scalar `history` field on any primitive: `false` off, `true` on at the default capture depth, a number = capture depth (how many statement executions are recorded per history record — NOT record retention), `"all"` unlimited.
1165
1223
  - **Omit `history` to inherit** — the engine resolves object → container → workspace at request time (a query inherits from its API group, a tool from its toolset envelope, everything else straight from the workspace). Any authored value stops inheriting for that object.
@@ -1170,11 +1228,11 @@ Runtime behavior (what the `as:` output holds, and misses):
1170
1228
  - **Workspace environment variables** set a tenant's env vars through the workspace object: `workspaceConfig({ env: { STRIPE_KEY: "", APP_BASE_URL: "" } })`, passed to `registerWorkspace()` — unattached, it declares nothing. Author them as a name→value MAP, declaring each NAME with an EMPTY value. Read a var back with `env("NAME")` (→ `$env.NAME`), which compiles to tag "setting" with the plain name.
1171
1229
  - Values are SECRETS and do NOT belong here: they live in `xano/.env`, which is gitignored and survives a `npx @xano/sdk pull`, and every command that compiles a bundle reads it with no flag. Fill it by hand from `xano/.env.example`, or run `npx @xano/sdk env pull`. CI passes `--backend-env-file <path>` or `--env-var KEY=VALUE` instead. A compiled bundle carries the values in cleartext — don't commit one.
1172
1230
  - What a deploy sends is the RESOLVED map (the declared names, then ONE file — `xano/.env`, or `--backend-env-file <path>` which REPLACES it, never both — then `--env-var`), not the literal object written here. `deploy` REPLACES the tenant's env with it, so a declared name with no value anywhere REFUSES the deploy rather than clearing the live value — fill the name in rather than putting the value back in source, and reach for `--allow-empty-env=NAME` only when clearing is what you mean.
1231
+ - A merge (`deploy --to`) is ADD-ONLY for env, matched BY NAME — it creates names the target lacks but does NOT update or remove ones it has, so the target's value wins. A release carries no env values, so a NEW name reads null after `promote`/`tenant deploy` until `env set` (both name it first). A `--replace` deploy DROPS every env var the target holds that the config does not declare (named, and confirmed, before it runs). Omit `env` entirely to leave existing env untouched. The separate `settings` field is a plain object.
1173
1232
 
1174
1233
  - **Workspace documentation** gates the workspace's hosted docs: `workspaceConfig({ documentation: { require_token: true } })`. `require_token: true` IS the declaration that a token exists; the value lives in `xano/.secrets.json`, keyed by the object it gates rather than by a name, and a literal `token` FAILS the export. It is NOT a backend env var — `env()` cannot read it. Other members are carried verbatim.
1175
- - ⚠ OMIT the block and NO `documentation` key is emitted, leaving the target's live block as it is; the legacy `realtime` block follows the same rule. An `apiGroup`'s `documentation` follows the OPPOSITE rule — see its def shape.
1234
+ - ⚠ OMIT the block and NO `documentation` key is emitted, leaving the target's live block as it is; the `realtime` block follows the same rule. An `apiGroup`'s `documentation` follows the OPPOSITE rule — see its def shape.
1176
1235
  - A declared gate with no token emits no block at all and REFUSES a `deploy`; `--allow-empty-doc-token=<scope>` clears that gate deliberately (scope = `workspace`, or an API group's NAME). `npx @xano/sdk pull` writes `xano/.secrets.json`, and `--no-secrets` writes none.
1177
- - A merge (`deploy --to`) is ADD-ONLY, matched BY NAME — it creates names the target lacks but does NOT update or remove ones it has, so the target's value wins. Two gaps: a release carries no env values, so a NEW name reads null after `promote`/`tenant deploy` until `env set` (both name it first) — and a `--replace` deploy rebuilds it so every env var the target holds that the config does not declare is DROPPED (named, and confirmed, before it runs). Omit `env` entirely to leave existing env untouched. The separate `settings` field is a plain object.
1178
1236
 
1179
1237
  # Auth, cross-object calls, and microservices
1180
1238
 
@@ -1182,85 +1240,113 @@ Runtime behavior (what the `as:` output holds, and misses):
1182
1240
 
1183
1241
  Auth & calls:
1184
1242
 
1185
- - `s.security.create_auth_token({ table, id, extras?, expiration?, as? })` — `extras` defaults to `{}`, `expiration` (seconds, a `Value`: `c.int(3600)`) to 86400 (`c.int(0)` = never).
1243
+ - `s.security.create_auth_token({ table, id, extras?, expiration?, as? })` — `extras` defaults to `{}`, `expiration` (seconds, a `Value`: `c.int(3600)`) to 86400 (`c.int(0)` = never). ⚠ Feeding `expiration` from an OPTIONAL int input mints a NEVER-expiring token when the client omits it: an omitted optional int binds `0`, and `0` means never — so `expiration: inp("ttl")` with an optional `ttl` silently issues permanent credentials. Declare `input.int({ default: 86400 })`, or leave `expiration` out in an `s.conditional` else branch when the input is null.
1186
1244
  - **Marketplace first:** `@xano-sdk/auth` registers a complete auth surface — signup/login/me endpoints plus their `user`/`account`/`event_log` tables — via `registerAuth(ws, { canonical: "authn" })`. Authentication only, not authorization. Inspect with `npx @xano/sdk marketplace details @xano-sdk/auth --prompt`.
1187
1245
  - **The auth loop end to end** — what that module implements; author it directly for a custom flow. An auth TABLE (`table({ auth: true })`) backs identity; a PUBLIC login query verifies and mints a token; every protected query names that table as `auth:` and reads the caller with `auth(...)`.
1188
- - Signup: `s.db.add({ table: users, row: { email: inp("email"), password: inp("password") } })` — the `f.password()` column hashes on write; take the submission as `input.text()` on signup AND login (see Gotchas on double-hashing).
1189
- - Login: `s.db.get({ table: users, fieldName: "email", fieldValue: inp("email"), output: ["id", "password"], as: "u" })` — the `output` naming `password` is REQUIRED (the column is `access: "internal"` and absent from the row otherwise) → `s.precondition({ expr: expr(ref("u", { safe: true }), "!=", c.null()), error: c.text("No such user."), error_type: "notfound" })` → `s.security.check_password({ text_password: inp("password"), hash_password: ref("u.password"), as: "ok" })` → precondition on `ok` → `s.security.create_auth_token({ table: users, id: ref("u.id"), as: "token" })` → `response: { token: ref("token") }`.
1190
- - Client: send it as an `Authorization: Bearer <token>` header. A `query({ auth: users })` refuses a request without a valid one before its stack runs; inside the stack `auth("id")` is the caller's row id (`response: { id: auth("id") }` is the whole `me` endpoint).
1191
- - **Authorization, on top of that.** `guard.role(users, "admin")` and `guard.owner("note", "user_id")` each return a fixed-arity TUPLE of statements — spread them (`stack: [...guard.role(users, "admin"), …]`); a helper returning `Statement[]` widens the stack and kills `InferResponse`.
1246
+ - Signup: `s.db.add({ table: users, row: { email: inp("email"), password: inp("password") } })` — the `f.password()` column hashes on write; take the submission as `input.text()` on signup AND login (a password input double-hashes; `llms.txt` Gotchas).
1247
+ - Login: `s.db.get({ table: users, fieldName: "email", fieldValue: inp("email"), output: ["id", "password"], as: "u" })` — the `output` naming `password` is REQUIRED (the column is `access: "internal"` and absent from the row otherwise) → `s.precondition({ expr: expr(ref("u", { safe: true }), "!=", c.null()), error: c.text("Invalid email or password."), error_type: "unauthorized" })` → `s.security.check_password({ text_password: inp("password"), hash_password: ref("u.password"), as: "ok" })` → precondition on `ok`, same error → `s.security.create_auth_token({ table: users, id: ref("u.id"), as: "token" })` → `response: { token: ref("token") }`. ⚠ One error for both: a 404/401 split enumerates accounts.
1248
+ - Client: send it as an `Authorization: Bearer <token>` header. A `query({ auth: users })` refuses a request without a valid one before its stack runs; inside the stack `auth("id")` is the caller's row id (`response: { id: auth("id") }` is the whole `me` endpoint). ⚠ The gate is STATELESS: it checks only the token's SIGNATURE and EXPIRY, never that the row still exists. A DELETED or disabled user's token keeps passing every `auth:` query until it expires (24 h by default), and `create_auth_token` mints for ANY id, so `auth("id")` can name a row that is gone — reads and ownership writes then serve or create rows for a ghost user. There is NO revocation; a short `expiration` is the only lever. Where it matters, verify the row exists: `s.db.get({ table: users, fieldValue: auth("id"), as: "__actor" })` → `guard.found("__actor", { errorType: "unauthorized" })` (`guard.role` already does this, answering 401 `Not signed in.`).
1249
+ - Claims: a token minted with `extras` is read back as `auth("extras.<key>")` (`auth("extras")` is the whole map). ⚠ A key ABSENT from the token (an older token, or one minted without it) is a 500 `Unable to locate auth: extras.<key>`, not null — mint the same keys every time. And claims are a SNAPSHOT frozen at mint: a role change does not reach existing tokens, so authorize off the row (`guard.role`) when the value can change, not off a claim.
1250
+ - **Authorization, on top of that.** `guard.role(users, "admin")` and `guard.owner("note", "user_id")` each return a fixed-arity TUPLE of statements — spread them (`stack: [...guard.role(users, "admin"), …]`).
1192
1251
  - `guard.role(table, role | roles[], { field?, as?, errorType?, message?, missingErrorType?, missingMessage? })` — fetches the caller's own row by `auth("id")` into `__actor`, asserts it EXISTS (401), then asserts its `role` is in the set (403). Roles type from the enum column; an unknown role or `field` throws. The existence step matters: a role check on a null actor row is not reliably false.
1193
- - `guard.owner(rowVar, ownerField = "user_id", { … })` — asserts the row bound to `rowVar` is non-null (404), THEN compares its owner column to `auth("id")` (also 404). Drilling before the existence check is a 500, not a denial: `db.get` binds `null` on a miss and `ref("note.user_id")` against it raises `Unable to locate var`. Takes the var NAME and the column separately for exactly that reason; a dotted path is refused.
1252
+ - `guard.owner(rowVar, ownerField = "user_id", { … })` — asserts the row bound to `rowVar` is non-null (404), THEN compares its owner column to `auth("id")` (also 404). Drilling before the existence check is a 500, not a denial: `db.get` binds `null` on a miss and `ref("note.user_id")` against it raises `Unable to locate var`. Takes the var NAME and the column separately; a dotted path is refused.
1194
1253
  - `guard.found(rowVar, { errorType?, message? })` — ONE statement: asserts the row bound to `rowVar` is non-null (404, `"Not found."`), and NARROWS it — after it, `InferResponse` drops the `| null` from `rowVar`. `guard.owner`'s existence step is this statement.
1195
1254
  - `guard.require(condition, { errorType?, message? })` for anything else — same shape, and it defaults to 403 where a bare `s.precondition` defaults to `standard`, i.e. **500**.
1196
1255
  - `s.security.create_uuid({ as? })` — bind a fresh UUID (v4). Takes nothing else. There is NO `create_guid` (internal, unpushable).
1197
1256
  - **Receiving a webhook** — no `auth`, no declared `input` (the signature covers the raw bytes): `s.util.get_raw_input({ encoding: "none", as: "raw" })` → `s.set_var("mac", withFilters(ref("raw"), fl.hmac_sha256(env("WH_SECRET"))))` → `s.set_var("sig", withFilters(sys.httpHeaders(), fl.get("X-Signature")))` (Title-Cased) → an `s.precondition` (`error_type: "unauthorized"`) comparing the two TIMING-SAFELY by HMACing both again — `expr(withFilters(ref("sig"), fl.hmac_sha256(env("WH_SECRET"))), "=", withFilters(ref("mac"), fl.hmac_sha256(env("WH_SECRET"))))` — BEFORE `fl.json_decode()` reads `raw`. Claim the event id with `s.redis.set({ …, create_only: c.bool(true) })` and answer 200 to a replay.
1198
- - `s.function.run({ fn, input?, as?, runtime? })` / `s.function.call({ fn, input?, as? })` — run another function; `input` is keyed by the target's input names (an undeclared one is a type and export error; generic over `fn`, pass `Record<string, Value>`; `2` binds an int — `c.decimal(2)` for a decimal). ⚠ `s.function.run` binds an input it OMITS from the CALLING def's same-named declared input — an endpoint declaring `discount` hands `?discount=100` through, or `0` when the client sends none. An endpoint/tool/prompt declaring NO inputs binds it from the raw request. `ignored()` always takes the target's default. Pass inputs explicitly (`statement.omitted-input` warns).
1199
- - `runtime?` runs it in the BACKGROUND: `{ mode: "async-shared" }` or `{ mode: "async-dedicated", cpu?, memory?, timeout?, maxRetry? }` (resources read at dedicated only). An async call DOES NOT return the result — it dispatches and continues, and `as` binds the job id (a UUID `string`); collect with `s.await({ ids, timeout, as })`, binding `{ "<jobId>": result }`; a too-short `timeout` or unknown id is a 500 `Async timeout`, no partial result. Omit for a normal call; same on `s.ai.agent.run`.
1257
+ - **Verifying a token (JWS/JWE)** — ⚠ `s.security.jws_decode`/`jwe_decode`/`decrypt`/`check_password` THROW a 500 `ERROR_FATAL` on EVERY failure (a tampered/garbage/empty/wrong-key token, a wrong `signature_algorithm`, an expired token `The token expired.`, a failed `check_claims` `Invalid value for claim: <k>`, a bad `decrypt` key/iv, a non-hash to `check_password`), NOT a falsy result — so a bare decode answers 500 for every bad token where 401 is wanted. Wrap it: `s.try_catch({ try: [s.security.jws_decode({ token: inp("token"), key: env("JWT_SECRET"), signature_algorithm: "HS256", check_claims: obj({ role: c.text("admin") }), as: "claims" })], catch: [s.precondition({ expr: expr(c.bool(true), "=", c.bool(false)), error_type: "unauthorized", error: c.text("Invalid token.") })] })` — a good token binds `claims` and runs on; any failure lands in `catch`, which raises a clean 401. `check_claims` is an object of EXACT-match claims; `exp`/`nbf` are checked automatically.
1258
+ - **`s.security.*` defaults are WEAK — pass them explicitly** (the catalog prints none; these are the engine's). `encrypt`/`decrypt` default `algorithm` to `aes-128-cbc`, so a 32-byte key is CUT to 16 (AES-128, not -256) — pass `algorithm: "aes-256-cbc"`. AES keys are NOT length-checked (a short key is zero-padded and still encrypts at 200), and a non-string `data` 500s — `fl.json_encode` an object first. `jws_encode`/`jwe_encode` default `ttl: 0`, which mints a token with NO `exp` claim (it NEVER expires) — set a `ttl` in seconds. `create_rsa_key` defaults `bits: 1024`, below the 2048 minimum — pass `bits: 2048`+. `random_bytes` defaults `length: 1`; `random_number` bounds are INCLUSIVE and `min > max` 500s; `create_password` with a `character_count` below the required classes 500s.
1259
+ - `s.function.run({ fn, input?, as?, runtime? })` / `s.function.call({ fn, input?, as? })` — run another function.
1260
+ - **Inputs:** `input` is keyed by the target's input names (an undeclared one is a type and export error, a mistyped `c.*` constant a type error; generic over `fn`, pass `Record<string, Value>`; `2` binds an int — `c.decimal(2)` for a decimal).
1261
+ - ⚠ **The two DIFFER ON FAILURE.** `s.function.run` RAISES — a `precondition`/500 in the target propagates, so the caller fails with that status, and an uncaught `s.throw` in it answers with its `status` (200 without one). `s.function.call` does NOT raise OUTSIDE a workflow test: it BINDS the error envelope `{ code, message, payload }` to `as` (still typed as the SUCCESS shape, so the mismatch is silent) and the stack answers 200 carrying it. Use `s.function.run` whenever a failing target must stop the caller; reach for `s.function.call` only to INSPECT a possible failure (branch on `ref("r.code")` before trusting the result). INSIDE a workflow test `s.function.call` DOES raise, like `s.api.call`/`s.task.call`.
1262
+ - ⚠ **Omitted inputs:** `s.function.run` binds an input it OMITS from the CALLING def's same-named declared input — an endpoint declaring `discount` hands `?discount=100` through, or `0` when the client sends none. An endpoint/tool/prompt declaring NO inputs binds it from the raw request. `ignored()` always takes the target's default. Pass inputs explicitly (`statement.omitted-input` warns).
1263
+ - ⚠ Forwarding a caller's OPTIONAL input (`input: { b: inp("b") }`) passes its EMPTY value (`0`/`""`) when the client omits it, NOT 'absent', so the TARGET's `default` never applies and you get wrong data at 200; declare the caller's input `nullable: true` (an omitted one then binds `null`, which DOES take the target's default) or repeat the default on the caller.
1264
+ - ⚠ **Depth:** calls nest at most ~25 deep per request (the engine's variable-stack limit); deeper, including legitimate bounded recursion (a tree walk, factorial, self-paginating call), fails with HTTP 500 `Infinite recursion detected` — recurse iteratively (`s.while` over an explicit list) or batch.
1265
+ - `runtime?` runs it in the BACKGROUND: `{ mode: "async-shared" }` or `{ mode: "async-dedicated", cpu?, memory?, timeout?, maxRetry? }` (resources read at dedicated only). Omit `runtime` for a normal call; same on `s.ai.agent.run`.
1266
+ - An async run keeps its caller: `auth()` inside it is the dispatching request's, and from a public endpoint it has none.
1267
+ - An async call DOES NOT return the result — it dispatches and continues, and `as` binds the job id (a UUID `string`). Collect with `s.await({ ids, timeout, as })`, binding `{ "<jobId>": result }` (read each with `fl.get(ref("<idVar>"))`); a too-short `timeout` or unknown id is a 500 `Async timeout`, no partial result.
1268
+ - ⚠ `s.await` NEVER RAISES for a FAILED job (only the timeout/unknown-id case 500s) — a crashed job's slot holds the error envelope in place of the result, served at HTTP 200, and `try_catch` cannot see it. Read each slot (`fl.get(ref("<idVar>"))`) and treat a present `code`/`statement`/`state` as a failure before trusting the result:
1269
+ - `{ code, message, payload }` for a precondition/engine error
1270
+ - `{ payload, statement }` for `s.throw` (no `code`)
1271
+ - `{ state: "terminated" }` for one stopped by `terminate`
1272
+ - ⚠ `ids` is a single `Value`, so a bare `[ref("j1"), ref("j2")]` fails `tsc` — pass one id as `ref("j1")`, or a list by building it first: `s.set_var("ids", obj({ list: [ref("j1"), ref("j2")] }))` then `s.await({ ids: ref("ids.list"), timeout: c.int(10), as })`.
1273
+ - Defaults: `ids` omitted → `{}` at once, `timeout` 10s; awaiting the same id twice returns the same result. `terminate: c.true()` asks every still-outstanding job to STOP at its next statement boundary when the await times out (its slot then reads `{ state: "terminated" }`); the await still throws `Async timeout`.
1200
1274
  - `s.api.call({ api, input?, headers?, auth?, as? })` — invoke an endpoint. WORKFLOW-TEST ONLY (see Gotchas in `llms.txt`).
1201
- - `api` takes the `query()` def HANDLE (or a `{ name, guid }` pair) — a bare name is refused, because a query's identity is composed from its api group, verb, and name.
1275
+ - `api` takes the `query()` def HANDLE (or a `{ name, guid }` pair) — a bare name is refused (identity = api group + verb + name).
1202
1276
  - `headers` REPLACES the request headers the callee sees and takes the same shapes as `s.api.request`'s, or one `Value`.
1203
- - `auth` is `{ token, ignoreExpiration? }`: `token` must be a BARE STRING — a tagged `Value` deploys clean and then fails the run with `Param: token - Text filter requires an integer, float, string or boolean value`, since the engine stores that slot as plain text and never evaluates it.
1204
- - Neither slot authenticates the call today; see `llms/tests.md` for what a workflow-test run actually sees.
1277
+ - `auth` is `{ token, ignoreExpiration? }`: `token` must be a BARE STRING — a tagged `Value` deploys clean and then fails the run with `Param: token - Text filter requires an integer, float, string or boolean value`.
1278
+ - Neither slot authenticates the call; see `llms/tests.md` for what a workflow-test run actually sees.
1205
1279
  - `s.api.request({ url, method?, params?, headers?, timeout?, follow_location?, verify_host?, verify_peer?, ca_certificate?, certificate?, certificate_pass?, private_key?, private_key_pass?, description?, output?, as? })` — external HTTP request (`mvp:api_request`). Ergonomic types, each also accepting a dynamic `Value`:
1206
- - `method` suggests the 7 verbs (GET/POST/PUT/DELETE/HEAD/OPTIONS/PATCH).
1280
+ - `method` suggests the 8 verbs (GET/POST/PUT/DELETE/HEAD/OPTIONS/PATCH/QUERY). QUERY (RFC 10008) is the safe method that sends `params` as its body.
1207
1281
  - `params` a plain JSON object **or** a FLAT record whose values are tagged `Value`s (`{ count: ref("count") }`, each lifted via a `set` filter — the same record-of-values shape `response: { key: value }` takes); a tagged value NESTED inside an object or array THROWS at encode, so wrap a structured body in `obj({...})`, which encodes any depth as one `const:expr2` (→ query string for GET/HEAD/OPTIONS, body otherwise).
1208
1282
  - `headers` a `{ "Name": value }` record whose values may be tagged (`{ "x-api-key": env("KEY") }`, each pair joined to a `"Name: value"` line) **or** a `string[]` of full header lines — prefer a header over a `?key=` query param for a credential — a URL reaches access logs and proxies.
1209
1283
  - ⚠ Neither spelling is envelope-safe: the `as` envelope's `request` half mirrors `url`, `params` AND `headers`, so never return it raw from a credentialed request — read `response.result`.
1210
1284
  - A NAME outside the header-token charset is refused, and a LITERAL value (string or `c.text`) carrying CR/LF/NUL is refused; a value may hold `:` and spaces (`Bearer a: b` is a valid value). A TAGGED value cannot be checked at build time, so strip CRLF from caller-controlled input before this slot. Literal pairs are emitted before computed ones, whatever the key order.
1211
1285
  - No `User-Agent` is sent unless `headers` carries one. An API requiring one answers **403** as ordinary `response.result` (no throw; every mapped field reads `null`). Send one (`headers: { "User-Agent": c.text("my-app") }`) and gate on `ref("<var>.response.status")` = 200 with `s.precondition`.
1212
- - A transport failure (timeout, DNS) does not throw — `s.try_catch` never catches it: `response.status` is `0`, with `response.error` set. Retry on `status == 0 || status >= 500`; `status < 500` passes a 0.
1286
+ - A transport failure (timeout, DNS) does not throw — `s.try_catch` never catches it: `response.status` is `0`, with `response.error` set. Retry on `status == 0 || status >= 500`; a bare `status < 500` check treats a transport failure (status 0) as success.
1213
1287
  - `timeout` a `number` in seconds (1–86400), and `follow_location`/`verify_host`/`verify_peer` booleans.
1214
1288
  - `description` and `output` filters ride the envelope. Cert pairings (certificate↔private_key, ca_certificate→verify_peer) are checked at build time when provable.
1215
1289
  - The `as` result is typed as the `{request, response}` envelope (`response.status: number`, `response.result: unknown`), so `InferResponse` resolves a `ref` to it. Same typed result on `webflow.request` and `microservice.request`.
1216
1290
  - `s.stream.from_request({ url, method?, …tls, as? })` — streaming external HTTP request (`mvp:streaming_api_request`); same typed field surface as `s.api.request` (no description/output envelope). `url` is REQUIRED.
1217
- - `s.util.send_email({ to, subject, message, from?, cc?, bcc?, reply_to?, service_provider?, api_key?, scheduled_at?, as? })` — send email from the stack. `service_provider` is `"xano"` (the built-in mailer — needs NO `api_key` and no configuration, and does not require a verified sender) or `"resend"` (pass the key as `api_key: env("RESEND_API_KEY")`). Prefer this over hand-rolling `s.api.request` against a mail provider.
1291
+ - `s.util.send_email({ to?, subject, message, from?, cc?, bcc?, reply_to?, service_provider?, api_key?, scheduled_at?, as? })` — send email from the stack. `subject` and `message` are required at runtime, and so are `to` and `from` with `"resend"`. Use it over a hand-rolled `s.api.request` to a mail provider.
1292
+ - `service_provider: "xano"` — the built-in mailer: needs NO `api_key` and no configuration, and does not require a verified sender. ⚠ It delivers ONLY to the workspace owner: `to`/`cc`/`bcc`/`reply_to`/`scheduled_at` are ignored and `from` is fixed — alerts to yourself, never mail to a user.
1293
+ - `service_provider: "resend"` — mail to any recipient; pass the key as `api_key: env("RESEND_API_KEY")`.
1294
+ - ⚠ A failed send does NOT raise: `as` binds `{ status: "error", error }` (success binds `status: "success"`). Branch on `ref("<as>.status")`.
1218
1295
  - `s.webflow.request({ path, method?, …tls, as? })` — Webflow API request (`mvp:connect_webflow_api_request`); like `s.api.request` but addressed by `path` (host is engine-supplied), and `path` is REQUIRED — the engine rejects an empty one. No `headers`: the engine builds its own from the workspace's Webflow connection and ignores an authored value.
1219
- - `s.task.call` / `s.tool.call` / `s.trigger.call` / `s.middleware.call` / `s.addon.call` — same `{ <target>, input?, as? }` shape against the named kind. `s.task.call` and `s.trigger.call` are WORKFLOW-TEST ONLY (see Gotchas in `llms.txt`); `s.tool.call`, `s.middleware.call` and `s.addon.call` run from any stack.
1220
- - `s.action.call({ actionId, input?, registry?, as? })` / `s.action.package.call({ traceId, versionId, slug, input?, registry?, as? })` — invoke an installed action. Ids are SUPPLIED, never derived from a name: an action is installed onto the instance, so its identity is assigned at install and differs per instance — read them off a call in a pulled workspace. The package form needs all three parts; they are one composite and two of them address nothing. `registry` is the action's own settings, `input` the per-call arguments.
1296
+ - `s.task.call({ task, as? })` — runs the task's stack once, now; takes NO `input` (a task declares none). `as` binds the task's `s.return` value (null without one), which is how a `workflowTest` asserts a task has a result. WORKFLOW-TEST ONLY (see Gotchas in `llms.txt`).
1297
+ - `s.tool.call` / `s.trigger.call` / `s.middleware.call` / `s.addon.call` — same `{ <target>, input?, as? }` shape against the named kind. `s.trigger.call` is WORKFLOW-TEST ONLY (see Gotchas in `llms.txt`); the other three run from any stack, but `s.tool.call` passes NO caller: `auth()` in the tool fails ACCESS_DENIED. ⚠ Like `s.function.call`, a FAILING tool never raises: its error envelope binds to `as` at 200; `s.function.run` a shared function to stop the caller.
1298
+ - `s.trigger.call`'s `input` is UNTYPED and must carry the inputs the target trigger reads, which the `t` accessor names: a `tableTrigger` needs `action` (`"insert"`/`"edit"`/`"delete"`), `datasource` (REQUIRED — without it the run fails `Missing param: datasource`), and `new`/`old` row objects; a misspelled key type-checks and is just ignored.
1299
+ - `s.action.call({ actionId, input?, registry?, as? })` / `s.action.package.call({ traceId, versionId, slug, input?, registry?, as? })` — invoke an installed action. Ids are SUPPLIED, never derived from a name: an action is installed onto the instance, so its identity is assigned at install and differs per instance — read them off a call in a pulled workspace. The package form needs all three parts: pass them together; any subset addresses nothing. `registry` is the action's own settings, `input` the per-call arguments.
1221
1300
  - `s.cloud.job({ image, command, args?, secret?, template?, await?, as? })` — launch a containerized job. `image`/`command` are REQUIRED; omitted → `Missing param`. ⚠ `await` is SECONDS (default 60), not a boolean.
1222
1301
  - `s.cloud.job.status({ id, as? })` · `s.cloud.job.await({ ids, timeout, as? })` — poll one job, or block on several (`ids` a list `Value`, `timeout` in seconds; both required).
1223
1302
 
1224
1303
  Microservices (the `microservice()` def and the statement that calls it):
1225
1304
 
1226
1305
  - `microservice({ name, kind, … })` — two mutually exclusive shapes via `kind`: `builtin` declares containers (image/ports/resources/env/command/args) plus optional `ingresses`, and `helm` points at a chart and its `values` — passing both throws.
1227
- - EARLY SURFACE, expected to change — every export of a workspace declaring one prints a notice saying so.
1306
+ - Unstable API — every export of a workspace declaring one prints a notice saying so.
1228
1307
  - `configs`/`volumes` are typed and `@deprecated` but NOT deployable: the engine rejects an import carrying either, so `export()` fails the build rather than letting the deploy fatal.
1229
1308
  - Put a value the workload reads in a container's `env`, and storage in a container's own `volumes` (`emptyDir`/`persistent`/`config`).
1230
1309
  - Container names are free-form — they need not match the microservice name, which is what a stack addresses.
1231
- - SECRETS RIDE ALONG — `chart.values` and `registryAuth.dockerconfigjson` are carried into the bundle, and into a pulled tree, verbatim. `process.env.X` in the def is NOT a way out: it resolves at EXPORT and writes the literal in.
1310
+ - ⚠ Secrets are copied verbatim: `chart.values` and `registryAuth.dockerconfigjson` are carried into the bundle, and into a pulled tree. `process.env.X` in the def is NOT a way out: it resolves at EXPORT and writes the literal in.
1232
1311
  - Reference a `workspaceConfig({ env })` var instead and only the NAME travels — the engine substitutes at DEPLOY. Two spellings: `env: [{ name: "API_KEY", fromEnv: "STRIPE_SECRET" }]` on a builtin container (`value`/`fromEnv` exclusive; both → build error), or `${env.NAME}` inside a helm `chart.values` (a VALUE at any depth, never a key). A name the workspace does not define FAILS the deploy rather than resolving blank.
1233
- - `registryAuth.dockerconfigjson` has NO such form: either leave it unset and pull a public image, or treat the bundle and any tree pulled from it as secret material — out of git, or rotate after. Export prints a notice per microservice carrying a literal; `--strict` does not promote it.
1312
+ - `registryAuth.dockerconfigjson` has NO such form: either leave it unset and pull a public image, or treat the bundle and any tree pulled from it as secret material — out of git, or rotate after. Export prints a notice per microservice carrying a literal; `--strict` does not fail on it.
1234
1313
  - `s.microservice.request({ host, path, port?, method?, params?, headers?, timeout?, follow_location?, as? })` — in-cluster microservice call (`mvp:microservice_request`); no TLS fields.
1235
1314
  - ONLY `host`+`path` required; the rest default to the engine's values (`GET`/`{}`/`[]`/`10`/`true`), always emitted.
1236
1315
  - Pass the `microservice()` DEF as `host` — it binds by NAME (how the engine resolves it), so a rename fixes every call site and the port is checked before deploy.
1237
1316
  - `port?` folds into `host` as `"name:port"`: a def exposing ONE `servicePort` resolves automatically, SEVERAL requires it.
1238
1317
  - A raw `"name:port"` string works, unvalidated, and is the only way to reach an instance-level microservice.
1239
1318
  - `tenantDeploy: "manual"` on the def imports the row without starting the workload.
1240
- - `s.workflow_test.call({ workflowTest, datasource?, as? })` — run another workflow test from inside one, which is the only place it runs (see Gotchas in `llms.txt`). The odd one out: NO `input` (a workflow test takes none), and it carries `datasource?` instead — same clone caveat as the kind's own field.
1319
+ - `s.workflow_test.call({ workflowTest, datasource?, as? })` — run another workflow test from inside one, which is the only place it runs (see Gotchas in `llms.txt`). NO `input`; `datasource?` has the kind's clone caveat.
1241
1320
 
1242
1321
  # Value catalog
1243
1322
 
1244
1323
  > Read when you need a literal, a reference, or a tag you have not used before — `c.*`, `ref`, `inp`, `auth`, `col`, and what each one encodes to.
1245
1324
 
1246
1325
  - `c.text(s: string) => Value` — String constant → tag "const".
1247
- - `c.int(n: number | bigint | string) => Value` — Integer constant → tag "const:int". The engine stores integers as STRINGS and has no 53-bit limit, so pass a string or bigint for anything past Number.MAX_SAFE_INTEGER — c.int("9223372036854775807") is exact where the number literal for it is already …808. A number that is not a safe integer THROWS rather than encoding the rounded value. The VALUE encodes at any width, but an `f.int` COLUMN is signed 64-bit and CLAMPS past its ceiling rather than failing — see `llms/fields.md`.
1326
+ - `c.int(n: number | bigint | string) => Value` — Integer constant → tag "const:int". The engine stores integers as STRINGS and has no 53-bit limit, so pass a string or bigint for anything past Number.MAX_SAFE_INTEGER — c.int("9223372036854775807") is exact where the number literal for it is already …808. A number that is not a safe integer THROWS rather than encoding the rounded value. For the int64 clamp of an `f.int` column see `llms/fields.md`.
1248
1327
  - `c.decimal(n: number | string) => Value` — Decimal constant → tag "const:decimal". Pass a string only to keep a stored spelling a number cannot reproduce (c.decimal("10.00") keeps its trailing zeros).
1249
- - `c.blank(tag: "const:<type>") => Value` — The editor's UNCONFIGURED value box (stored value ""), emitted by codegen for a pulled workspace — do not author it. NOT a zero or an empty collection: the engine reads "" and "0" differently, so c.blank("const:int") ≠ c.int(0) and neither canonicalizes into the other. Constant tags except const/const:obj, whose blanks are c.text("")/c.obj(null).
1328
+ - `c.blank(tag: "const:<type>") => Value` — The editor's UNCONFIGURED value box (stored value ""), emitted by codegen for a pulled workspace — do not author it. NOT a zero or an empty collection: the engine reads "" and "0" differently, so c.blank("const:int") ≠ c.int(0) and neither canonicalizes into the other. Valid for every constant tag except `const` and `const:obj`; their blanks are `c.text("")` and `c.obj(null)`.
1250
1329
  - `c.bool(b: boolean) => Value` — Boolean constant → tag "const:bool".
1251
1330
  - `c.null(tag?: "const:null" | "const:obj") => Value` — Null constant, stored value "null". Bare c.null() is tag "const:null". c.null("const:obj") is the OBJECT-TYPED null the engine writes into a db.* statement's @meta slot — different stored bytes from c.obj(null), which is the blank object (value ""), though both evaluate to null. Codegen emits whichever spelling the workspace stored; do not swap one for the other.
1252
- - `c.obj(o?: Json | null) => Value` — Object constant → tag "const:obj". A populated one stores an empty {} carrying one `set` filter per key — the editor's form, and the only populated form the engine reads back (a populated JSON string arrives truncated and fails the request with ERROR_FATAL "Unable to decode."). ⚠ a ZERO-BASED numeric key is an INDEX in the engine's data model, so c.obj({"0":"a"}) evaluates to the list ["a"] (a non-zero-based one like {"2":…} survives as a key) — that is the platform, not this encoding. Write c.array([...]) for a list, or prefix the keys ("k0") for an object; `export()` warns. No argument = the empty object {} — use this one. Explicit null = the legacy blank form the engine evaluates to null, NOT {}; it exists only so a pulled workspace round-trips, do not author it. Plain JSON literals only — a nested tagged value (inp/ref/auth/c.*) is rejected; for a computed object response use a record of values, not c.obj.
1331
+ - `c.obj(o?: Json | null) => Value` — Object constant → tag "const:obj". A populated one stores an empty {} carrying one `set` filter per key (a populated JSON string fails the request with ERROR_FATAL "Unable to decode."). ⚠ A ZERO-BASED numeric key is an INDEX: c.obj({"0":"a"}) evaluates to the list ["a"] ({"2":…} stays a key) — write c.array([...]) for a list, or prefix the keys ("k0") for an object; `export()` warns. c.obj() is the empty object {}. c.obj(null) is a pulled-workspace blank that evaluates to null; do not author it. Plain JSON literals only — a nested tagged value (inp/ref/auth/c.*) is rejected; for a computed object use a record of values.
1253
1332
  - `c.array(a: Json[]) => Value` — Array constant (JSON string) → tag "const:array". Plain JSON literals only — a nested tagged value is rejected, same as c.obj.
1254
- - `c.expression(source: string) => Value` — Xano Expression Engine source, passed through VERBATIM → tag "const:expr2". The string IS the expression: c.expression('"Hi, " ~ $input.name'), c.expression("$var.price * $var.qty"). ⚠️ NOT VALIDATED — never parsed or type-checked, invisible to InferResponse, and untouched by a rename that updates every typed ref(); a typo surfaces at runtime or as a wrong answer. Use it ONLY for syntax the typed surfaces cannot express (~ concatenation, inline arithmetic, conditionals) — prefer ref/inp/col, withFilters+fl.*, and obj() (which BUILDS a checked expression). Not the expr() condition builder.
1255
- - `c.now() => Value` — Current time as epoch-ms — the engine-native const:epochms constant (no filter). Valid inline as a where/cmp operand. For cutoff math (cutoff = now - max_age) either compare inline or, for reuse/readability, hoist it into an s.set_var and compare against the var.
1256
- - `obj(fields: Record<string, Value | nested>) => ObjValue<typeof fields>` — Dynamic object value → tag "const:expr2" (an object-literal expression string). The dynamic sibling of c.obj: members may be inp/ref/auth values, env()/setting()/sys.*, c.now(), c.* constants, nested records, or arrays — and each member may carry a FILTER CHAIN (withFilters + fl.*), which renders as the expression pipe `$var.row|get:"a.b"`. A null-safe ref(path, { safe: true }) works inside an obj() member directly. The member record rides the return type, so InferResponse (through a set_var too) resolves each member like a top-level response key — `response: { user: obj({ id: ref("row.id") }) }` derives `{ user: { id: Col | null } }`, and a raw nested object literal (`response: { user: { id: ref("row.id") } }`, auto-wrapped through this) derives the same. A constant record or list has two spellings that both work and render identically: bare (`{ a: 1 }`, `[]`) or `c.obj(...)`/`c.array([...])` — prefer the bare form. An inner obj() nests, same bytes as a raw record. The legacy blank `c.obj(null)` is refused here (it evaluates to null, not {}) — write c.null() or c.obj(). Still rejected: a filter ARGUMENT that carries its own chain or is a c.now() (a trailing | binds to the whole value, not one argument, and c.now() needs one), a DISABLED filter (an expression string cannot record that), and the output/response/trycatch/toolset/reg tags (a type error) — set_var those first and ref() them.
1333
+ - `c.expression(source: string) => Value` — Xano Expression Engine source, passed through VERBATIM → tag "const:expr2". The string IS the expression: c.expression('"Hi, " ~ $input.name'), c.expression("$var.price * $var.qty"). ⚠ Unvalidated: not parsed, typed (invisible to InferResponse), or renamed with refs; a typo surfaces at runtime. Use only for syntax typed surfaces lack (`~`, inline arithmetic, conditionals); otherwise prefer ref/inp/col, withFilters+fl.*, and obj() (which builds a checked expression). Not the expr() condition builder.
1334
+ - `c.now() => Value` — Current time as epoch-ms — the engine-native const:epochms constant. Valid inline as a where/cmp operand.
1335
+ - `obj(fields: Record<string, Value | nested>) => ObjValue<typeof fields>` — Dynamic object value → tag "const:expr2" (an object-literal expression string); the dynamic sibling of c.obj.
1336
+ - Members: inp/ref/auth values, env()/setting()/sys.*, c.now(), c.* constants, nested records, or arrays. Each may carry a FILTER CHAIN (withFilters + fl.*), rendered as the expression pipe `$var.row|get:"a.b"`. A null-safe ref(path, { safe: true }) works in a member directly. An inner obj() nests, same bytes as a raw record.
1337
+ - InferResponse (through a set_var too) resolves each member like a top-level response key: `response: { user: obj({ id: ref("row.id") }) }` derives `{ user: { id: Col } }`, and a raw nested object literal (`response: { user: { id: ref("row.id") } }`, auto-wrapped through this) derives the same.
1338
+ - A constant record or list has two spellings that both work and render identically: bare (`{ a: 1 }`, `[]`) or `c.obj(...)`/`c.array([...])` — prefer the bare form.
1339
+ - Rejected: the blank `c.obj(null)` is refused here (write c.null() or c.obj()); a filter ARGUMENT that carries its own chain or is a c.now(); a DISABLED filter; the output/response/trycatch/toolset/reg tags (a type error) — set_var those first and ref() them.
1257
1340
  - `ref(name: string, opts?: { safe?: boolean }) => Value` — Reference a stack variable → tag "var". Pass { safe: true } for null-safe nested access — a dotted ref("owner.user_id", { safe: true }) compiles through the get filter so it resolves to null instead of raising "Unable to locate var" when the base is null.
1258
- - `inp(name: string) => Value` — Reference a function/endpoint input → tag "input". Resolves ONLY against the `input` block of the def it sits in — a value produced earlier in the stack is `ref("var.field")`, not `inp("field")`. A name that is not declared here deploys clean and fails at runtime with ERROR_FATAL "Unable to locate input: <name>" on every branch that reads it; `export()` warns, and `--strict` fails the build. Sending the name in the request does NOT rescue it — an undeclared input is never bound, so the call fails identically with the value present. A dotted path drills INTO a declared input (`inp("action.amount")` needs a declared `action`).
1341
+ - `inp(name: string) => Value` — Reference a function/endpoint input → tag "input". Resolves ONLY against the `input` block of the def it sits in — a value produced earlier in the stack is `ref("var.field")`, not `inp("field")`. A name that is not declared here deploys clean and fails at runtime with ERROR_FATAL "Unable to locate input: <name>" on every branch that reads it; `export()` warns, and `--strict` fails the build. Sending the name in the request does NOT rescue it. A dotted path drills INTO a declared input (`inp("action.amount")` needs a declared `action`). ⚠ An omitted/`null` optional input binds its EMPTY value (`""`/`0`/`false`/`[]`/`{}`; `""` for an enum), not null — only a type whose input defaults to `nullable: true` (vector, uuid, date, timestamp, file types; `llms/fields.md`) or one set `nullable: true` binds null. An omitted optional `input.geo.*` is not bound at all.
1259
1342
  - `col(name: string) => Value` — Reference a table column → tag "col".
1260
- - `auth(path?: string) => Value` — Reference the authenticated identity (auth("id") → $auth.id) → tag "auth".
1343
+ - `auth(path: string) => Value` — Reference the authenticated identity (auth("id") → $auth.id) → tag "auth". The PATH is required: the engine cannot read a bare auth, so auth("") throws. A token minted with extras exposes its claims at auth("extras.<key>") (auth("extras") is the whole map); a key absent from the token is a 500, not null.
1261
1344
  - `caught(path?: "code" | "message" | "name" | "result") => Value` — Read the caught error inside an s.try_catch CATCH arm → tag "trycatch". Valid ONLY there — it reads empty in the try/finally arms and outside the statement. Those four fields are all the engine binds; bare caught() is the whole error record. `code` is the error type: `ERROR_FATAL` for an engine error, a precondition's `error_type` (`ERROR_CODE_ACCESS_DENIED`, …), `ERROR_CODE_THROWN_ERROR` for `s.throw`. `message` is the error text (a precondition's `error`, the engine's, an LLM provider's) EXCEPT for `s.throw`, where it is the fixed "Throw Error Statement" and your value is in `result`. `name` is `s.throw`'s `name` (empty without one), else a label (`Exception`, `Access Denied`). ⚠ An `s.ai.agent.run` provider failure binds `result: { name: "AI_APICallError", statusCode, isRetryable, data }`; branch a fallback on `withFilters(caught("result"), fl.get("statusCode"))` (401: the key was refused). The path takes only the four names; reach deeper with `fl.get`.
1262
1345
  - `toolset(path: "token" | "params" | `params.${string}`) => Value` — Read a toolset-scoped binding inside a tool → tag "toolset". The engine binds two: token (the calling URL's token, null when absent) and params (its parameters, as an object); a dotted params.<key> reads one parameter out of that object. Bound only while a tool runs under its toolset — anywhere else it reads empty.
1263
- - `env(name: string) => Value` — Read a WORKSPACE environment variable (set via workspaceConfig({ env }) or the dashboard) → `$env.NAME`. Compiles to tag "setting" with the plain name. env("remote_ip") reads a user var named remote_ip, not the caller IP — use sys.remoteIp() for that. A name that does not exist resolves to NULL rather than erroring, so a typo deploys clean and fails downstream of the value: prefer typedEnv(config), which turns the names that config declares into properties (E.STRIPE_KEY), and export() warns stack.env-undeclared on any env() or bare setting() outside the declared set once a config declares env at all.
1346
+ - `env(name: string) => Value` — Read a WORKSPACE environment variable (set via workspaceConfig({ env }) or the dashboard) → `$env.NAME`. Compiles to tag "setting" with the plain name.
1347
+ - Every value is TEXT (or null), edge whitespace trimmed on read: compare a flag against c.text("true"), not c.bool(true) (under loose `=`, FLAG=false equals c.bool(true)); a numeric use needs fl.to_int/fl.to_decimal.
1348
+ - env("remote_ip") reads a user var named remote_ip, not the caller IP — use sys.remoteIp().
1349
+ - A name that does not exist resolves to NULL rather than erroring, so a typo deploys clean: prefer typedEnv(config), which turns the names that config declares into properties (E.STRIPE_KEY). Once a config declares env, export() warns stack.env-undeclared on any env() or bare setting() outside the declared set.
1264
1350
  - `setting(name: string) => Value` — Reference a workspace setting → tag "setting". Built-in system vars are $-prefixed settings, e.g. setting("$remote_ip"); prefer the typed sys.* accessors.
1265
1351
  - `sys.*() => Value` — Built-in system / request-context variables → tag "setting" ($-prefixed). Accessors: remoteIp, requestMethod, requestUri, requestQueryString, httpHeaders, requestAuthToken, apiBaseUrl, datasource, branch, tenant, release, platform, isDebugger. In XanoScript these are $env.$remote_ip etc.; sys.remoteIp() is the public-endpoint rate-limit key (auth("id") is null there). sys.httpHeaders() keys arrive Title-Cased whatever the client sent: a client sending `x-sync-secret` is read as `X-Sync-Secret`, so `get:"x-sync-secret"` is null in production — read the Title-Cased name. s.api.call sends header names the same way, so a workflow test sees what a real request delivers.
1266
1352
  - `filter(name: string, ...args: Value[]) => FilterXdo` — Build a filter-chain entry by raw name (escape hatch).
@@ -1277,19 +1363,22 @@ Author table columns + function/API inputs with the typed catalog: `f.<type>(opt
1277
1363
  for columns, `input.<type>(opts?)` for inputs. Common opts: `required`, `nullable`,
1278
1364
  `default`, `description`, `access` (a read omits `"internal"` columns, returns `"private"` ones; `InferRow`
1279
1365
  is the full row, both kept), `sensitive` (masks the input's value in request logs; a read still RETURNS a sensitive column — `access: "internal"` keeps it out).
1280
- **`nullable` defaults PER TYPE, matching the engine's own column-creation API**: `true`
1281
- for `f.vector`, `f.uuid`, every `f.geo.*` and every file type (`f.image`/`f.video`/
1282
- `f.audio`/`f.attachment`), `false` for everything else (text, int, decimal, bool, email,
1283
- enum, json, object, password, date, tableRef); inputs add date, timestamp and file, so an
1284
- omitted one binds `null` (a `required` one still accepts an explicit `null`). Pass `nullable` to override —
1285
- e.g. `f.geo.polygon({ nullable: false })`. An empty default becomes NULL only when
1366
+ ⚠ On a column, `required` is not a write-time constraint: `db.add`/`edit` store a null, `""`, or (after a `trim` method) whitespace-only value at HTTP 200 — it only shapes the seed write-shape, the typed row, and the editor. Enforce presence on the input (`input.*({ required: true })` plus a non-empty check — a `min: 1` method or an `s.precondition`).
1367
+ ⚠ An `f.date` COLUMN does not validate the written value: an invalid calendar date ROLLS OVER into a different valid one (`"2020-13-45"` stores `"2021-02-14"`) instead of failing, so a value arriving through `input.text`/`input.json` or a computed var is silently corrupted. Validate at the boundary with `input.date` (it rejects the same string with a 400).
1368
+ **`nullable` defaults per type**: `true` for `f.vector`, `f.uuid`, every `f.geo.*` and every
1369
+ file type (`f.image`/`f.video`/`f.audio`/`f.attachment`); `false` for the rest. Inputs add
1370
+ date, timestamp and file, so an omitted one binds `null`
1371
+ (a `required` one still accepts an explicit `null`). Pass `nullable` to override.
1372
+ ⚠ Except `input.geo.*`: an omitted optional geo input is not bound at all, so `inp("p")` 500s `Unable to locate input: p`. Mark it `required: true`, or read it only inside an `s.conditional` that a sibling flag gates.
1373
+ An empty default becomes NULL only when
1286
1374
  nullable, so a non-null `f.vector(8)` column fails to create (`''` is not a vector).
1287
1375
  **`f.geo.*` values are `{ type, data }`, not GeoJSON.** The same shape goes in and comes
1288
1376
  back. `type` per column: `point` → `"point"`, `data` `{ lng, lat }`; `multipoint` → `"points"`,
1289
1377
  `linestring` → `"path"`, `polygon` → `"poly"` (ring closed for you), `data` `[{ lng, lat }, …]`;
1290
1378
  `multilinestring` → `"paths"`, `multipolygon` → `"polys"`, `data` `[[{ lng, lat }, …], …]`.
1291
1379
  Any other spelling (`"multipoint"`, `"linestring"`, `"Point"`) 400s `Only strings are supported for:`.
1292
- Raw WKT text (`c.text("POINT(1 2)")`) is accepted on write too, but a read never returns one.
1380
+ Raw WKT text (`c.text("POINT(1 2)")`) is accepted on write too, but a COLUMN read never returns one.
1381
+ ⚠ An `input.geo.*` is the exception: `inp("p")` inside the stack reads back as WKT TEXT (`"POINT(10 20)"`), NOT the `{ type, data }` you POSTed — it becomes `{ type, data }` only once WRITTEN to a geo column and read back. So `InferResponse` of a bare `inp()` of a geo input is wrong (it types `{ type, data }`); treat a bound geo input as a `string`.
1293
1382
  `methods` (validators/transforms, names per type below): `"trim"`, `"min:8"`
1294
1383
  (a text arg keeps its `:`: `"startsWith:https://"`), or `{ name, arg }` — for unlisted names and `pattern`'s error text.
1295
1384
  `f.json({children})` declares the nested shape stored INSIDE a json column — an ARRAY of
@@ -1297,10 +1386,11 @@ Raw WKT text (`c.text("POINT(1 2)")`) is accepted on write too, but a read never
1297
1386
  `f.object` takes positionally. Omit it for an unstructured json column.
1298
1387
  `f.enum(values)`/`f.vector(size)`/`f.object(children)`/`f.tableRef(table)` take a
1299
1388
  positional payload before opts — and still accept the standard `FieldOptions` after it
1300
- (`f.enum([])`/`input.enum([])` are accepted: a pulled enum with no options, not one to
1301
- author — it brands the column `never`, which `InferRow` surfaces as `undefined`.)
1302
1389
  (e.g. `f.tableRef(users, { required: true })` — only `min`/`max` are listed as tableRef
1303
- methods below, but `required`/`nullable`/`description`/… apply like any field.)
1390
+ methods below, but `required`/`nullable`/`description`/… apply like any field).
1391
+ `f.enum([])`/`input.enum([])` (a pulled enum with no options) brands the column `never`; `InferRow` surfaces it as `undefined`.
1392
+ ⚠ An `f.enum` column refuses a non-member (400) but STORES `""`, which an omitted optional
1393
+ `input.text`/`input.enum` binds, overriding the `default`; `InferRow` types it members `| ""`. Declare that input `nullable: true` (omitted → `null` → the default).
1304
1394
  An **OPTIONAL foreign key wants a `0` sentinel, not `nullable: true`**. `f.tableRef` to an int-keyed table stores
1305
1395
  an `int`, and a null in it is unqueryable: `null` is never a legal `fieldValue`/`id`, so
1306
1396
  `s.db.get`/`edit`/`del` on that column answer HTTP 400 `Missing param: field_value` rather
@@ -1311,10 +1401,11 @@ binds `null`, which is the answer the null was reaching for. `export()` warns on
1311
1401
  An `f.vector(size)` column is SEARCHED through `s.db.query`'s `eval` pipeline, not through
1312
1402
  any `SearchOp`: give the table `index: [{ type: "vector", fields: [{ name: "embedding", op:
1313
1403
  "vector_cosine_ops" }] }]`, then rank with a distance filter + a sort on its alias (see
1314
- `s.db.query` → `eval`). Without that pairing the column stores and indexes but nothing
1315
- queries it.
1404
+ `s.db.query` → `eval`).
1316
1405
  `{ array: true }` makes any `f.*` scalar a **list column** — `f.text({ array: true })`
1317
- surfaces as `string[]` in `InferRow<typeof table>` (the column analogue of `input.list`).
1406
+ surfaces as `string[]` in `InferRow<typeof table>`.
1407
+ Filter one to rows containing a value with `contains`/`overlaps` and a LIST operand (NOT a
1408
+ scalar — `llms/statements-data.md`).
1318
1409
  **Seed a table's starting rows with `table({ seed })`.** `seed` takes rows
1319
1410
  typed against the table's schema as a WRITE shape (a column without
1320
1411
  `required: true`, and the system columns, may be omitted; `null` needs
@@ -1339,7 +1430,7 @@ Omit `id` and rows auto-number `1..N` (int PK) or take
1339
1430
  a stable derived uuid (uuid PK); supplying `id` pins it (and
1340
1431
  resets an int sequence past the max). All-or-nothing — mixing explicit and
1341
1432
  omitted `id` throws. A `system:false` PK is the author's to supply. Pinning is
1342
- `seed`-only — `s.db.bulk.add` DROPS `id` unless `allowIdField: true`.
1433
+ `seed`-only — `s.db.bulk.add` DROPS `id` unless `allowIdField: true`. ⚠ After a deploy, the FIRST insert into an UNSEEDED int-keyed table gets `id: 2`, not 1 (a seeded table continues correctly from its max) — so a test or fixture must not assume the first inserted row is `id: 1`.
1343
1434
  **`use_xdo` storage mode.** Workspace setting (`registerWorkspace({ use_xdo })`,
1344
1435
  default `false`): `true` stores fields as JSON in the `xdo` column (+ `gin(xdo)` index),
1345
1436
  `false` real columns.
@@ -1348,10 +1439,10 @@ A **column `default` must stay within the BMP** — a 4-byte character (codepoin
1348
1439
  e.g. an emoji) is rejected at export; put such a value on an `input.<type>({ default })`.
1349
1440
  `input.*` mirrors `f.*` — every column type below is
1350
1441
  a legal input (scalars, files `input.image/video/audio/attachment`, `input.geo.*`,
1351
- `input.vector(size)`, `input.tableRef(table)`, `input.object(children)`), plus
1352
- `input.dbLink(table)` is the odd one: ONE entry that EXPANDS into one input per
1353
- COLUMN of the linked table, so read them by column name (`inp("email")`), never by
1354
- the entry's own name. `hidden: ["created_at"]` drops columns from that expansion.
1442
+ `input.vector(size)`, `input.tableRef(table)`, `input.object(children)`).
1443
+ Input-only: `input.dbLink(table)` expands into one input per column of the linked table;
1444
+ read them by column name (`inp("email")`), not by the entry's own name.
1445
+ `hidden: ["created_at"]` drops columns from that expansion.
1355
1446
  `input.list(element)` for arrays — wrap any element constructor, e.g.
1356
1447
  `input.list(input.text())` or `input.list(input.object({ id: f.int() }))`.
1357
1448
  **A file reaches a column in two steps.** `input.file` is the RAW upload (the request's
@@ -1363,6 +1454,7 @@ multipart/base64 bytes) and cannot be written to a file column directly: store i
1363
1454
  `"public"` (a guessable URL): pass `"private"` and hand out `s.storage.sign_private_url`
1364
1455
  results for anything user-scoped. `create_video`/`create_audio`/`create_attachment` are
1365
1456
  the same shape for the other file columns, each fed `input.file` (`input.image`/… 400s an upload).
1457
+ ⚠ A WRONG-KIND upload to `create_image`/`create_audio`/`create_video` (text sent as an image, or a `.txt` renamed `.png`) fails the request with HTTP 500 `ERROR_FATAL` (`Invalid file extension.` / `This resource is not a valid image.`), not a 4xx. Guard it: wrap the store in `s.try_catch`, or precondition the upload's extension/mime first.
1366
1458
  **An empty file column is a stored null that `where` does not see as null.** `expr(col("file"), "!=", c.null())`
1367
1459
  matches EVERY row, and `= c.null()` matches none. Compare a key inside the file instead:
1368
1460
  `expr(col("file.path"), "!=", c.null())` keeps only the rows holding a file.
@@ -1372,6 +1464,9 @@ malformed address with a 400 (and trims; add `methods: ["lower"]` to downcase)
1372
1464
  `regex_matches` needed; `input.int`/`input.decimal`/`input.uuid`/`input.enum([...])`/`input.date`
1373
1465
  likewise reject or coerce bad input at the boundary. Drop to `input.text` + `s.precondition`
1374
1466
  only for rules no type expresses.
1467
+ ⚠ `input.int` COERCES by TRUNCATION, not refusal: a fractional number binds its integer part
1468
+ at HTTP 200 (`1.7` → `1`, `2.9` → `2`), where `"abc"` gets a 400. When a fraction must be
1469
+ refused rather than silently floored, take `input.decimal` and check it with `s.precondition`.
1375
1470
  ⚠ `input.url` is NOT one of them — there is no engine `url` type, so it stores as `text`
1376
1471
  and validates NOTHING: a `javascript:`/`data:` URL type-checks, imports, and binds. When the value gets navigated
1377
1472
  to, check the scheme in the stack. It is INPUT ONLY — there is no `f.url` column.
@@ -1380,25 +1475,39 @@ SECONDS (`date +%s`) bind in January 1970 with no error. An ISO-8601 string keep
1380
1475
  offset but DROPS fractional seconds (`"…T19:30:00.123Z"` binds `…:00.000`). Send epoch ms
1381
1476
  (`Date.now()`, `getTime()`) whenever sub-second precision matters.
1382
1477
  ⚠ `input.list` does NOT reject a non-array: one value binds as a ONE-item list (`"a"` →
1383
- `["a"]`), and a non-JSON string given to an `input.object` binds an object of its
1384
- children's DEFAULTS — so `input.list(input.object({...}))` given `"notalist"` binds
1385
- `[{ name: "", … }]` with a 200. A list `min` does not catch it (that is one item). A string
1386
- starting with `[` is parsed as JSON with NO element check at all. When the shape must hold,
1387
- mark an object child `required: true` (the default-filled object then 400s with its param
1388
- path) and check anything else with `s.precondition`.
1389
- ⚠ `s.precondition`'s `error` must be a TAGGED value — `c.text("…")`, not a bare string.
1390
- The engine falls back to the generic "Precondition failed." whenever it reads an empty or
1391
- non-scalar message, and a bare string lands there, so the client never sees your text. The
1392
- `error_type` → HTTP status mapping is correct either way; only the message is lost.
1478
+ `["a"]`); a non-JSON string given to an `input.object` binds an object of its
1479
+ children's DEFAULTS, so `input.list(input.object({...}))` given `"notalist"` binds
1480
+ `[{ name: "", … }]` with a 200 (a list `min` passes: one item). A string starting with `[`
1481
+ is parsed as JSON with NO element check. To enforce the shape, mark an object child
1482
+ `required: true` (the default-filled object then 400s with its param path); check the rest
1483
+ with `s.precondition`.
1484
+ ⚠ `s.precondition`'s `error` must be a TAGGED value — `c.text("…")`, not a bare string (warns `stack.precondition-bare-error`).
1485
+ A bare string is replaced by the generic "Precondition failed."; the status from `error_type` still applies.
1393
1486
  `error_type` is how a stack sets a FAILURE status: `badrequest`/`inputerror` → 400, `unauthorized` → 401, `accessdenied` → 403, `notfound` → 404, `toomanyrequests` → 429, `standard` → 500.
1487
+ A failed request answers a JSON envelope `{ code, message, payload }`: `code` is the
1488
+ `ERROR_CODE_*` string for the `error_type` (`badrequest` → `ERROR_CODE_BAD_REQUEST`,
1489
+ `accessdenied` → `ERROR_CODE_ACCESS_DENIED`, `notfound` → `ERROR_CODE_NOT_FOUND`, …;
1490
+ `standard`/an uncaught engine error → `ERROR_FATAL`). `message` is the `error` text.
1491
+ `payload` is `s.precondition`'s optional structured detail (`obj({...})`), client-visible;
1492
+ it is `""` when a precondition sets none and the key is ABSENT entirely on engine errors.
1493
+ ⚠ A `db.edit`/`db.del` NotFound carries an EMPTY `message` (just `{code:"ERROR_CODE_NOT_FOUND"}`),
1494
+ so a `catch` that re-raises `fl.concat(caught("message"))` yields only its prefix and an
1495
+ `expect.to_throw(c.text(...))` can never match it — re-raise with your own `error` text.
1496
+ ⚠ An uncaught `s.throw` (including one inside a function run with `s.function.run`):
1497
+ - answers HTTP **200** with `{ payload, statement: "Throw Error" }`, so `res.ok` is true — UNLESS it
1498
+ sets `status`: `s.throw({ name: "NOT_ALLOWED", value: c.text("no access"), status: 403 })`
1499
+ answers 403 with that body (`status` is a whole number, 100–599).
1500
+ - The status applies only when nothing catches the throw; a caught throw leaves the response status alone.
1501
+ - The body carries `value` as `payload` and never the `name`.
1502
+ - For the `{ code, message, payload }` envelope, fail with `s.precondition` or `guard.require` instead.
1503
+
1394
1504
  For any other status — and for a redirect — use `respond.*`, which is sugar over
1395
1505
  `s.util.set_header` (that statement reaches the status line): `respond.status(201)`,
1396
1506
  `respond.redirect(url, { status?: 301|302|303|307 })` (a TUPLE — spread it; a `Location`
1397
1507
  alone does NOT redirect), and `respond.header(name, value)`. Position in the stack does not
1398
1508
  matter, a later status wins, and a FAILING `precondition` still wins over anything set
1399
1509
  before it. ⚠ `204` answers with an empty body whatever `response` says. ⚠ `respond.status`
1400
- REFUSES `308`/`425`/`451`/`102`/`103`: the platform writes those and does not act on them,
1401
- so the response is 200 with nothing reported — use 301, 429 and 403 instead.
1510
+ REFUSES `308`/`425`/`451`/`102`/`103` (they would answer 200, nothing reported); use 301, 429 and 403 instead.
1402
1511
  Normalizing transforms run on bind too — put `trim`/`lower`/`upper` on the input's `methods`
1403
1512
  so `inp("name")` reads already-normalized; don't reroll `var $x = inp("name")|trim` in the stack.
1404
1513
  ⚠ `f.decimal`'s size depends on the table's layout; it takes no precision or scale option.
@@ -1452,38 +1561,45 @@ text or BigInt. `c.int()` refuses an unsafe number literal, so pass the string.
1452
1561
 
1453
1562
  Attach to a value with `withFilters(v, fl.name(...))` — the value `filters[]`
1454
1563
  pipeline. Filters are passed spread (canonical); the array form
1455
- `withFilters(v, [fl.a(), fl.b()])` is also accepted. Every filter is typed:
1456
- the ones below carry named args, and the rest take NO arguments — call them
1457
- `fl.<name>()`, and passing an argument is a compile error.
1458
- A typed filter's declared argument list is an EXACT count, not a floor: passing more
1459
- than it lists THROWS, in the type and at runtime. The extra argument used to ride into
1460
- the filter's arg list, where the engine either ignores it or fails opaquely on a live
1461
- endpoint. `filter("name", …)` is the untyped escape for a filter the catalog
1462
- under-declares. Seven declared filters are exceptions the engine really does take more from, so they
1463
- stay variadic: `concat` (trailing separator), `index_by` (trailing list flag), `get` (trailing variable
1464
- map), `array_merge` and `array_merge_recursive` (any number of arrays), `jwe_encode` and
1465
- `jwe_decode`. To send more than a zero-argument filter's `()` accepts, use the same
1466
- `filter("name", …)` escape. A filter with NO declared list takes nothing and is emitted
1467
- `()` — except the variadic few listed under the catalog, which take arguments the
1468
- catalog never declared and so are not arity-checked at all.
1564
+ `withFilters(v, [fl.a(), fl.b()])` is also accepted. Every filter is typed. Arity:
1565
+
1566
+ - A declared argument list (the catalog below) is an EXACT count, not a floor: passing more
1567
+ THROWS, in the type and at runtime.
1568
+ - Seven declared filters take more: `concat` (trailing separator), `index_by` (trailing list
1569
+ flag), `get` (trailing variable map), `array_merge`/`array_merge_recursive` (any number of
1570
+ arrays), `jwe_encode`, `jwe_decode`.
1571
+ - A filter with NO declared list is called `fl.<name>()`; passing an argument is a compile
1572
+ error. The variadic filters at the end of the catalog take undeclared arguments and are
1573
+ not arity-checked.
1574
+ - Past any of these — a filter the catalog under-declares, or more than a
1575
+ zero-argument filter's `()` accepts — use the untyped `filter("name", …)`.
1576
+
1469
1577
  A typed filter also accepts one object of NAMED arguments (`fl.add({ value: 1 })`); a key
1470
1578
  the filter does not declare throws rather than being dropped.
1471
1579
  A bare JS **scalar** — string, number or boolean — is accepted in ANY `fl.*` argument and
1472
- wrapped as the constant you would have written by hand (`fl.get("a.b", 0)` encodes
1473
- identically to `fl.get(c.text("a.b"), c.int(0))`). An object or array must still be built
1474
- with `c.obj`/`c.array`. Any argument also takes a runtime value (`inp`, `ref`, a
1475
- `withFilters` chain) — inside `obj()`/`expr()` an argument cannot carry its own filter
1476
- chain, so compute it in a prior `set_var`. The arg types below name each argument's
1477
- ENGINE type, not the JS type you may pass.
1478
- `fl.add`/`fl.sub`/`fl.mul` keep an INT when both operands are ints (`2 × 3` is `6`, not
1479
- `6.0`) and give a decimal only when either operand is one — the `decimal` return type
1480
- below covers both, so an int pipeline needs no `fl.to_int()`. `fl.div` is an int only
1580
+ wrapped as a constant (`fl.get("a.b", 0)` ≡ `fl.get(c.text("a.b"), c.int(0))`). Build an
1581
+ object or array with `c.obj`/`c.array`. Any argument also takes a runtime value (`inp`, `ref`,
1582
+ a `withFilters` chain); inside `obj()`/`expr()` an argument cannot carry its own filter
1583
+ chain — compute it in a prior `set_var`. Arg types below are ENGINE types, not JS types.
1584
+ `fl.add`/`fl.sub`/`fl.mul` keep an INT when both operands are ints (`2 × 3` is `6`) and give
1585
+ a decimal when either is one; an int pipeline needs no `fl.to_int()`. `fl.div` is an int only
1481
1586
  when it divides exactly.
1482
1587
  To add to a numeric column (counter, stock, balance), use `s.db.increment`
1483
1588
  (`llms/statements-data.md`) — one atomic UPDATE. A pipeline read-modify-write is NOT
1484
1589
  atomic (concurrent writers lose updates), and `col("clicks")` does NOT resolve to the
1485
1590
  stored value inside a `db.edit` `row` (it is `null`; `null + 1` aborts): `db.get` the row
1486
1591
  `as: "current"`, then `withFilters(ref("current.clicks"), fl.add(c.int(1)))`.
1592
+ ⚠ NULL operands, by filter:
1593
+ - Text filters (`trim`/`upper`/`strlen`/`to_int`/…) pass null through (`strlen(null)` is `null`;
1594
+ `strlen` of a non-string is `null` too, not a length).
1595
+ - Arithmetic treats null as `0` (`null|add:1` → `1`).
1596
+ - `fl.concat` on a null or list base returns `""` and SILENTLY DROPS its argument
1597
+ (`null|concat:"x"` → `""`). Default the base first:
1598
+ `withFilters(inp("middle"), fl.first_notnull(c.text("")), fl.concat("x"))`.
1599
+ - `fl.split` of null is `[""]`.
1600
+
1601
+ ⚠ `fl.trim`/`ltrim`/`rtrim` (and the `s.text.*` trims) take `mask` as a SET OF CHARACTERS, not a
1602
+ substring. It is a PHP MASK, so `"a..c"` means the RANGE a-c, not the three characters `a`, `.`, `c`.
1487
1603
 
1488
1604
  - `fl.add(value: decimal): decimal`
1489
1605
  - `fl.append(value: <T>, path: text): <T>[]`
@@ -1505,7 +1621,7 @@ stored value inside a `db.edit` `row` (it is `null`; `null + 1` aborts): `db.get
1505
1621
  - `fl.array_set(path: text, value: any): obj` — sets a DOTTED path and returns the value; a non-object piped value is replaced by an empty one
1506
1622
  - `fl.array_slice(offset: int, length?: int): <T>[]`
1507
1623
  - `fl.array_unshift(value: <T>): <T>[]`
1508
- - `fl.array_upmerge(match: obj, node: obj): <T>[]` — merges the node INTO each matched element; `array_replace` swaps the element whole
1624
+ - `fl.array_upmerge(match: obj, node: obj): <T>[]` — merges the node into the FIRST matched element, and APPENDS it on a miss (an UPSERT, not update-all) — use `fl.map` to update every match; `array_replace` is first-match too but swaps the element whole and THROWS on a miss
1509
1625
  - `fl.base_convert(from_base: any, to_base: any): text`
1510
1626
  - `fl.bitwise_and(value: int): int`
1511
1627
  - `fl.bitwise_or(value: int): int`
@@ -1527,32 +1643,32 @@ stored value inside a `db.edit` `row` (it is `null`; `null + 1` aborts): `db.get
1527
1643
  - `fl.decrypt(algorithm: enum, key: text, iv: text): text`
1528
1644
  - `fl.detect_encoding(encodings?: text): text`
1529
1645
  - `fl.div(value: decimal): decimal`
1530
- - `fl.encrypt(algorithm: enum, key: text, iv: text): text`
1646
+ - `fl.encrypt(algorithm: enum, key: text, iv: text): text` — binds RAW ciphertext bytes — fl.base64_encode() before returning or storing (fl.decrypt takes the raw bytes back)
1531
1647
  - `fl.ends_with(search: text): bool` — piped value is the subject text; the arg is the substring searched for
1532
1648
  - `fl.epochms_add_ms(milliseconds: int): epochms`
1533
1649
  - `fl.epochms_add_secs(seconds: int): epochms`
1534
1650
  - `fl.epochms_date(format: text, timezone?: text): text`
1535
1651
  - `fl.epochms_from_format(format: text, timezone?: text): text`
1536
- - `fl.epochms_transform(format: text, timezone?: text): text` — applies a relative shift (e.g. "+1 day") to the timestamp
1652
+ - `fl.epochms_transform(format: text, timezone?: text): int` — applies a relative shift (e.g. "+1 day") to the timestamp. ⚠ a format `strtotime` cannot parse yields `0`, and a MISTYPED one (`"+1 dya"`) a PLAUSIBLE WRONG time, both with NO error — see date-filter failure modes in `llms/statements-runtime.md`
1537
1653
  - `fl.eq(value: <T>): bool`
1538
- - `fl.every(code: text, timeout?: int): any[]` — `code` is a JS body run per element (true for all?), over `$this`/`$index`/`$parent`
1654
+ - `fl.every(code: text, timeout?: int): bool` — `code` is a JS body run per element (true for all?), over `$this`/`$index`/`$parent` — returns a BOOL (`true` on an empty list)
1539
1655
  - `fl.filter(code: text, timeout?: int): any[]` — `code` is a JS body run per element (keep it? true/false), over `$this`/`$index`/`$parent`
1540
- - `fl.filter_empty(path?: text): <T>[]` — keeps entries that are not empty ("", null, 0, "0", false, [], {})
1656
+ - `fl.filter_empty(path?: text): <T>[]` — keeps entries that are not empty ("", null, 0, "0", false, [], {}) — the only one of the family that drops them all
1541
1657
  - `fl.filter_empty_array(path?: text): <T>[]`
1542
1658
  - `fl.filter_empty_object(path?: text): <T>[]`
1543
- - `fl.filter_empty_text(path?: text): <T>[]`
1659
+ - `fl.filter_empty_text(path?: text): <T>[]` — drops only `""`; null, 0, false, [] and {} stay
1544
1660
  - `fl.filter_false(path?: text): <T>[]`
1545
1661
  - `fl.filter_null(path?: text): <T>[]`
1546
- - `fl.filter_zero(path?: text): <T>[]`
1547
- - `fl.find(code: text, timeout?: int): any[]` — `code` is a JS body run per element; returns the first element it accepts
1548
- - `fl.findIndex(code: text, timeout?: int): any[]` — `code` is a JS body run per element; returns the first matching index
1662
+ - `fl.filter_zero(path?: text): <T>[]` — drops only the integer `0` (strict), not `"0"` or `0.0`
1663
+ - `fl.find(code: text, timeout?: int): <T>` — `code` is a JS body run per element; returns the first ELEMENT it accepts (`null` when none)
1664
+ - `fl.findIndex(code: text, timeout?: int): int` — `code` is a JS body run per element; returns the first matching INDEX as an int (`-1` when none)
1549
1665
  - `fl.first_notempty(value: any): any` — first value that is not empty ("", null, 0, "0", false, [], {})
1550
1666
  - `fl.first_notnull(value: any): any`
1551
- - `fl.fsort(path?: text, type?: "text"|"itext"|"natural"|"inatural"|"number", asc?: bool): <T>[]` — `type` is the comparator, and ONLY "number" compares numerically — "text"/"itext" are strcmp/strcasecmp, "natural"/"inatural" are the human-readable "a2 < a10" orderings. Default "itext". Anything else silently sorts as text, so a numeric sort MUST spell "number"; the path arg drills into each element
1552
- - `fl.get(path: text, default?: json): any` — `path` may be a runtime value: after `fl.index_by("suite_id")`, `fl.get(ref("suite.id"))` returns that key's rows (null for a missing key)
1667
+ - `fl.fsort(path?: text, type?: "text"|"itext"|"natural"|"inatural"|"number", asc?: bool): <T>[]` — `type` is the comparator: "number" (the only numeric one), "text"/"itext" (strcmp/strcasecmp), "natural"/"inatural" ("a2 < a10"). Default "itext"; anything else sorts as text. The path arg drills into each element
1668
+ - `fl.get(path: text, default?: json): any` — `path` may be a runtime value: after `fl.index_by("suite_id")`, `fl.get(ref("suite.id"))` returns that key's rows (null for a missing key). ⚠ the `default` applies only to a MISSING path — a key present with a `null` value stays `null`; chain `fl.first_notnull(default)` to cover both.
1553
1669
  - `fl.gt(value: <T>): bool`
1554
1670
  - `fl.gte(value: <T>): bool`
1555
- - `fl.has(path: text): bool`
1671
+ - `fl.has(path: text): bool` — `false` for a missing key and for a key whose value is `null` (unlike `fl.get`'s default, which treats a present null as present)
1556
1672
  - `fl.hmac_md5(key: text, raw?: bool): text`
1557
1673
  - `fl.hmac_sha1(key: text, raw?: bool): text`
1558
1674
  - `fl.hmac_sha256(key: text, raw?: bool): text`
@@ -1585,32 +1701,32 @@ stored value inside a `db.edit` `row` (it is `null`; `null + 1` aborts): `db.get
1585
1701
  - `fl.pow(exp: <T>): decimal`
1586
1702
  - `fl.prepend(value: <T>, path: text): <T>[]`
1587
1703
  - `fl.range(start: int, stop: int): int[]`
1588
- - `fl.reduce(initial_value: int, code: text, timeout?: int): any[]` — `code` is a JS body run per element; the ACCUMULATOR is `$result` (there is no `$acc`) and `initial_value` is REQUIRED — omitting it would slot the code as the initial value
1704
+ - `fl.reduce(initial_value: any, code: text, timeout?: int): any` — `code` is a JS body run per element; the ACCUMULATOR is `$result` (there is no `$acc`) and `initial_value` is REQUIRED. `initial_value` takes ANY value (an object/text accumulator, `c.obj({...})`/`c.text("")`, not just an int); the result is that accumulator
1589
1705
  - `fl.regex_match(subject: text): text[]` — piped value is the PATTERN, the arg is the subject — see `regex_test`
1590
1706
  - `fl.regex_match_all(subject: text): text[]` — piped value is the PATTERN, the arg is the subject — see `regex_test`
1591
1707
  - `fl.regex_quote(delimiter?: text): text`
1592
1708
  - `fl.regex_replace(replacement: text, subject: text): text` — piped value is the PATTERN, `subject` is the text searched — see `regex_test`. The replacement comes FIRST
1593
- - `fl.regex_test(subject: text): bool` — piped value is the PATTERN (build it with `c.regex(...)`); the arg is the subject — the REVERSE of `contains`/`starts_with`. Swapped, it answers false for every input with no error, so write `withFilters(c.regex("^a+$"), fl.regex_test(inp("s")))` (or name the arg: `fl.regex_test({ subject: inp("s") })`). A pattern found in the subject slot is refused at build time
1709
+ - `fl.regex_test(subject: text): bool` — piped value is the PATTERN (build it with `c.regex(...)`); the arg is the subject — the REVERSE of `contains`/`starts_with`. Swapped args → always false, no error. Write `withFilters(c.regex("^a+$"), fl.regex_test(inp("s")))` (or name the arg: `fl.regex_test({ subject: inp("s") })`). A pattern found in the subject slot is refused at build time
1594
1710
  - `fl.round(precision?: int): decimal`
1595
1711
  - `fl.rtrim(mask?: text): text`
1596
- - `fl.secureid_decode(salt: text): int`
1597
- - `fl.secureid_encode(salt: text): text`
1712
+ - `fl.secureid_decode(salt: text): int` — a wrong salt, or a garbage/empty id, is a 400 (`This signature is invalid.` / `Invalid input format for secureId.`), NOT null — wrap in s.try_catch to handle a miss; only the id from `secureid_encode` of a non-negative int round-trips back
1713
+ - `fl.secureid_encode(salt: text): text` — the operand must be a NON-NEGATIVE integer — a negative or fractional one encodes without error but `secureid_decode` returns a DIFFERENT positive int (`-3` → `13`, `-42` → `214`, `1.5` → `1`), NOT a round-trip; validate the domain before encoding
1598
1714
  - `fl.set(path: text, value: any): any`
1599
1715
  - `fl.set_conditional(path: text, value: any, conditional: any): any`
1600
1716
  - `fl.set_ifnotempty(path: text, value: any): any`
1601
1717
  - `fl.set_ifnotnull(path: text, value: any): any`
1602
1718
  - `fl.sha1(raw?: bool): text`
1603
- - `fl.sha256(raw?: bool): text`
1719
+ - `fl.sha256(raw?: bool): text` — the optional `raw` arg returns RAW binary, not the hex digest — fl.bin2hex()/fl.base64_encode() it before returning or storing (strlen then UNDER-COUNTS: it counts characters, not bytes); omit `raw` for hex
1604
1720
  - `fl.sha384(raw?: bool): text`
1605
1721
  - `fl.sha512(raw?: bool): text`
1606
- - `fl.some(code: text, timeout?: int): any[]` — `code` is a JS body run per element (true for any?), over `$this`/`$index`/`$parent`
1722
+ - `fl.some(code: text, timeout?: int): bool` — `code` is a JS body run per element (true for any?), over `$this`/`$index`/`$parent` — returns a BOOL (`false` on an empty list)
1607
1723
  - `fl.splice(offset: int, length?: int, path?: text): <T>[]` — returns the REMOVED slice, not the remainder — [1,2,3,4] spliced at offset 1 length 2 yields [2,3]; with a `path` it removes in place and returns the whole value instead
1608
1724
  - `fl.split(separator: text): text[]`
1609
1725
  - `fl.starts_with(search: text): bool` — piped value is the subject text; the arg is the substring searched for
1610
1726
  - `fl.string_replace(search: text, replacement: text): text`
1611
1727
  - `fl.strip_tags(exclude?: text): text`
1612
- - `fl.stripos(search: text): int`
1613
- - `fl.strpos(search: text): int`
1728
+ - `fl.stripos(search: text): int|false`
1729
+ - `fl.strpos(search: text): int|false`
1614
1730
  - `fl.sub(value: decimal): decimal`
1615
1731
  - `fl.substr(start: int, length: int): text`
1616
1732
  - `fl.to_epoch_day(timezone?: text): int`
@@ -1621,17 +1737,19 @@ stored value inside a `db.edit` `row` (it is `null`; `null + 1` aborts): `db.get
1621
1737
  - `fl.to_epochms(timezone?: text): epochms`
1622
1738
  - `fl.transform(expression: text): any` — `expression` is Xano Expression Engine source, NOT a JS body — no `return`, and the piped value is `$0` (or `$$`), NOT `$this` (which is null here). `$var`/`$input`/`$env`/`$auth` resolve and filters pipe inside it: `$0 * 2`, `$0|sort|join:","`. Parenthesize a pipe inside an object literal — `{ s: ($0|sort|join:",") }` — or its comma is read as the key separator and later keys vanish silently. For JavaScript use `lambda`
1623
1739
  - `fl.trim(mask?: text): text`
1624
- - `fl.unique(path?: text): <T>[]`
1740
+ - `fl.unique(path?: text): <T>[]` — with a `path`, dedupes a list of records by the value at that path and keeps the FIRST per key — but it DROPS every element whose path is missing or null (the same rule as `index_by`), so deduping by an optional key loses those rows
1625
1741
  - `fl.unpick(keys: text): <T>` — returns the object without the named keys (inverse of a pick)
1626
1742
  - `fl.unset(path: text): any`
1627
1743
  - `fl.url_addarg(key: text, value: text, encoding_rfc3986?: bool): text`
1628
1744
  - `fl.url_delarg(key: text): text`
1629
1745
  - `fl.url_getarg(key: text, default?: text): text`
1630
- - `fl.url_hasarg(key: text): text`
1746
+ - `fl.url_hasarg(key: text): bool`
1631
1747
  - `fl.yaml_encode(options?: bool, inline?: int, indent?: int): text`
1632
1748
 
1633
- Zero-argument filters, by operand type — call as `fl.<name>()`; an argument is a compile error. array: array_entries, array_keys, array_lower, array_pop, array_shift, array_shuffle, array_values, count, first, flatten, last, reverse, rsort, safe_array; comparison: bitwise_not, empty, even, is_array, is_bool, is_decimal, is_int, is_object, is_text, is_uuid, not, odd; geo: to_geo_linestring, to_geo_multilinestring, to_geo_multipoint, to_geo_multipolygon, to_geo_point, to_geo_polygon; math: abs, acos, acosh, asin, asinh, atan, atanh, avg, ceil, cos, deg2rad, exp, floor, ln, log10, product, rad2deg, sin, sqrt, sum, tan; misc: null; other: sort; security: uid, uuid4; text: addslashes, capitalize, escape, from_utf8, list_encodings, lower, querystring_parse, sql_alias, sql_esc, strip_accents, strlen, text_escape, text_unescape, to_utf8, upper, url_parse; timestamp: ms_to_secs, secs_to_ms; transform: base64_decode, base64_decode_urlsafe, base64_encode, base64_encode_urlsafe, bin2hex, bindec, create_object_from_entries, decbin, dechex, decoct, hex2bin, hexdec, json_decode, json_encode, octdec, to_bool, to_decimal, to_expr, to_int, to_text, url_decode, url_decode_rfc3986, url_encode, url_encode_rfc3986, xml_decode, yaml_decode.
1749
+ Zero-argument filters, by operand type: array: array_entries, array_keys, array_lower, array_pop, array_shift, array_shuffle, array_values, count, first, flatten, last, reverse, rsort, safe_array; comparison: empty, even, is_array, is_bool, is_decimal, is_int, is_object, is_text, is_uuid, not, null, odd; geo: to_geo_linestring, to_geo_multilinestring, to_geo_multipoint, to_geo_multipolygon, to_geo_point, to_geo_polygon; math: abs, acos, acosh, asin, asinh, atan, atanh, avg, bitwise_not, ceil, cos, deg2rad, exp, floor, ln, log10, product, rad2deg, sin, sqrt, sum, tan; other: sort; security: uid, uuid4; text: addslashes, capitalize, escape, from_utf8, list_encodings, lower, querystring_parse, sql_alias, sql_esc, strip_accents, strlen, text_escape, text_unescape, to_utf8, upper, url_parse; timestamp: ms_to_secs, secs_to_ms; transform: base64_decode, base64_decode_urlsafe, base64_encode, base64_encode_urlsafe, bin2hex, bindec, create_object_from_entries, decbin, dechex, decoct, hex2bin, hexdec, json_decode, json_encode, octdec, to_bool, to_decimal, to_expr, to_int, to_text, url_decode, url_decode_rfc3986, url_encode, url_encode_rfc3986, xml_decode, yaml_decode.
1634
1750
  `fl.reverse()` reverses a list only: on a text value it answers the text UNCHANGED, with no error.
1751
+ An unknown `timezone` (a typo, `+05:30`, `PDT`) silently means UTC. A literal warns at export; take a runtime zone as an `input.enum`.
1752
+ `fl.to_bool()` is NOT a truthiness cast: it accepts only the boolean vocabulary — `true`/`1`/`"1"`/`"true"`/`"on"`/`"yes"` and `false`/`0`/`"0"`/`"false"`/`"off"`/`""` — and ANY other value 400s `ERROR_CODE_INPUT_ERROR` "Invalid boolean input.". For a truthiness cast pipe `fl.ne(c.int(0))`.
1635
1753
 
1636
1754
  Variadic filters — they take arguments, but no declared list, so the count is not checked: sprintf.
1637
1755
 
@@ -1639,19 +1757,15 @@ Variadic filters — they take arguments, but no declared list, so the count is
1639
1757
 
1640
1758
  > Read when writing a JavaScript body, or weighing whether to reach for one at all — `lam.fn`, `fl.lambda`, `fl.reduce`, `s.lambda`; each surface binds a different set of identifiers.
1641
1759
 
1642
- **A lambda is an escape hatch, not a default.** The body runs outside the request's own
1643
- runtime, and a workspace has a BOUNDED pool of lambda workers every lambda in it shares
1644
- — so a call both crosses a process boundary and draws on a workspace-wide resource.
1645
- Reach for one only when the typed surface cannot express the work: if a native filter,
1646
- an `expr(...)`/`obj(...)` expression, or a plain statement can, use that. The crossing
1647
- is per CALL, not per element — an iterating filter sends the body ONCE and loops on the
1648
- other side, so one body over a whole list beats one called from inside a stack loop.
1760
+ **A lambda is an escape hatch, not a default.** Use one only when a native filter,
1761
+ an `expr(...)`/`obj(...)` expression, or a statement can't do the work: each call crosses a
1762
+ process boundary into a BOUNDED pool of lambda workers every lambda in the workspace shares.
1763
+ The crossing is per CALL, not per element — an iterating filter sends the body ONCE and loops on the
1764
+ other side, so one iterating filter over a list beats a lambda inside a stack loop.
1649
1765
 
1650
1766
  The lambda statement (`s.lambda({ as, code, timeout? })`) and eight filters run a
1651
- JavaScript body. **Write the body as a FUNCTION, not a `c.text` string** — the
1652
- bindings are its parameters, so the editor supplies them and a wrong name is a
1653
- compile error instead of a wrong value at runtime. Write it inline and the surface
1654
- is implied by where it sits; nothing names one:
1767
+ JavaScript body. **Write the body as a FUNCTION, not a `c.text` string** (bindings are
1768
+ typed parameters; a wrong name is a compile error). Inline, the surface is implied by where it sits:
1655
1769
 
1656
1770
  ```ts
1657
1771
  fl.map(({ $this }) => $this * 2) // map's bindings, typed from the position
@@ -1659,19 +1773,18 @@ fl.reduce({ initial_value: 0, code: ({ $result, $this }) => $result + $this })
1659
1773
  s.lambda({ as: "total", code: ({ $var }) => $var.subtotal * 1.2 }) // ambient only — $this is a compile error
1660
1774
  ```
1661
1775
 
1662
- The parameters are a fiction — only the BODY is sent, and the engine injects the
1663
- bindings as free identifiers — so DESTRUCTURE them as named: `(b) => b.$this`,
1664
- `{ $this: x }`, nesting, a default or rest are undefined there (refused).
1776
+ Destructure bindings by their exact names (`({ $this })`). Refused: `(b) => b.$this`,
1777
+ renaming (`{ $this: x }`), nesting, defaults, rest.
1665
1778
 
1666
1779
  ⚠ An inline `code:` arrow receives BINDINGS ONLY. `capture` is an option of
1667
1780
  `lam.fn`, not a field of `s.lambda` or a filter, so `capture:` beside `code:` is a type
1668
- error — the fix is to relocate the body, not to drop the field: `lam.fn(fn, { capture })` (below).
1781
+ error — move the body into `lam.fn(fn, { capture })` (below).
1669
1782
 
1670
1783
  For a body built away from its call site:
1671
1784
 
1672
1785
  - `lam.fn(({ $result, $this }) => $result + $this, { surface?, capture? })` — name a `surface` to check it here, or omit it and the call site checks it.
1673
1786
  - `lam.raw("return 1", { surface })` — text, same validation.
1674
- - `lam.raw(code, { surface, unchecked: true })` — sends a body that does not parse or declares a top-level `import`/`export` (a fixture pinning the engine's syntax-error answer, or a pulled body); skips those syntax checks only, here and at the `s.lambda` / `fl.*` site.
1787
+ - `lam.raw(code, { surface, unchecked: true })` — sends a body that does not parse or declares a top-level `import`/`export`; skips those syntax checks only, here and at the `s.lambda` / `fl.*` site.
1675
1788
  - `lam.file("./lambdas/total.ts")` — a default-exported function in its own module (path relative to the caller), read as text at build time. NODE ONLY: `import { lam } from "@xano/sdk/node"` (isomorphic `lam` has no `file`). Only the default export's BODY is sent, so a value import, a second export or a top-level helper is refused — move helpers inside; `import type` / `import { type X }` are free. `@xano/sdk/lambda-globals` types the globals below program-wide: keep modules in `xano/lambdas/` (its scaffold tsconfig loads it) or `import type {} from` it under their own tsconfig.
1676
1789
 
1677
1790
  Nothing from the enclosing scope crosses: the body is sent as TEXT, so a closed-over
@@ -1682,13 +1795,12 @@ body needs in `capture`; it arrives as the SECOND parameter, emitted as a `const
1682
1795
  lam.fn(({ $this }, { capturedRate }) => $this * capturedRate, { surface: "map", capture: { capturedRate: rate } })
1683
1796
  ```
1684
1797
 
1685
- ⚠ A capture key must NOT share its name with a module-scope binding: a `.ts` loader
1686
- renames one of two same-named bindings, so the body reads `rate2` while the prelude
1687
- declares `rate` (refused at build time). `capture: { capturedRate: rate }` is the safe form.
1798
+ ⚠ A capture key must NOT share a module-scope binding's name (a `.ts` loader renames one;
1799
+ refused at build time) — `capture: { capturedRate: rate }`, not `{ rate }`.
1688
1800
 
1689
1801
  Capture JSON data only: a function, `NaN`, a sparse/typed array or class instance (`Date`, `Map`…)
1690
1802
  is refused at build time, at any depth. Capture the plain form and rebuild in
1691
- the body (`d.getTime()` → `new Date(d)`). The captured type flows into the second parameter.
1803
+ the body (`d.getTime()` → `new Date(d)`).
1692
1804
 
1693
1805
  A body is a FUNCTION BODY: it must `return` its value. Bindings by surface — an
1694
1806
  identifier outside its surface's set is undefined at runtime, and the SDK refuses
@@ -1705,12 +1817,21 @@ an iterating filter and the piped value in `fl.lambda`; `$parent` is the whole a
1705
1817
  and exists only on the iterating filters. A stack variable is reached as
1706
1818
  `$var.name` — it is NOT also injected as a bare `$name`.
1707
1819
 
1708
- Four hazards and the dependency route, all live-verified:
1709
-
1710
- - ⚠ A body that THROWS does not fail the request: the engine returns its diagnostic
1711
- TEXT as the value with HTTP 200, so the failure reads as bad data. Validate before
1712
- consuming a lambda result numerically, and prefer a `lam.*` body, which cannot fail
1713
- this way for a binding reason.
1820
+ `$auth` with no authenticated caller (a public surface, or an authed one reached without a
1821
+ token) is `{ id: 0, dbo: "" }`, not null. Test `$auth.id > 0`, not truthiness.
1822
+
1823
+ Hazards:
1824
+
1825
+ - ⚠ A body that THROWS or times out does not fail the request (nor reach `s.try_catch`): the
1826
+ engine returns its diagnostic TEXT as the value with HTTP 200 (`"[Line 1:Char 7] boom"`,
1827
+ `"Lambda timed out after 1 seconds"`; a thrown non-Error is `" Unknown error"` on the cloud).
1828
+ Validate before consuming it. To FAIL the request: wrap the body in `try { return { ok: true,
1829
+ v } } catch { return { ok: false } }`, then `s.precondition` `ref("r.ok", { safe: true })` = `true`.
1830
+ - ⚠ An `s.lambda` whose body returns a STRING that parses as a JSON object or array binds
1831
+ the DECODED value, not the string (the statement's output is cast as `json`);
1832
+ scalar-looking strings (`"123"`, `"true"`) stay text, and `fl.map`/`fl.lambda` keep
1833
+ the string. A body that `JSON.stringify`s a payload to sign/hash/store gets an object
1834
+ back. To keep text, return it WRAPPED (`{ text }`) and read `.text`.
1714
1835
  - ⚠ `timeout` is COOPERATIVE — observed only at an `await` — so it bounds WAITING (a slow
1715
1836
  `fetch`), not compute: a 1s `timeout` over a 3s busy-loop runs all 3s and returns
1716
1837
  normally. Bound a loop that could run away inside the body.
@@ -1718,19 +1839,28 @@ Four hazards and the dependency route, all live-verified:
1718
1839
  a dependency through the PRELOADED globals below. A dynamic `import("…")`/`require("…")`
1719
1840
  with a LITERAL specifier is not portable: an instance that bundles the body first
1720
1841
  returns the TEXT `Could not resolve "node:crypto"` with HTTP 200.
1721
- - Preloaded globals, live-probed — no specifier, so these work everywhere:
1842
+ - Preloaded globals — no specifier, so these work everywhere:
1722
1843
  `_` · `aws4` · `axios` · `cryptojs` · `DateTime` · `ethers` · `fastXmlParser` ·
1723
1844
  `jose` · `luxon` · `mailparser` · `math` · `moment` · `nodemailer` · `socks` ·
1724
1845
  `uuid` · `utils`
1725
1846
  …plus `fetch`, `Buffer`, `TextEncoder`/`TextDecoder`, and the `crypto` above
1726
1847
  (`randomUUID`, `createHmac`, `createHash`, `subtle`). `Object.keys(globalThis)`
1727
1848
  inside a body lists whatever else a given instance carries.
1728
- - ⚠ `console` output goes to the request LOG, not stdout. `log` · `error` · `warn` ·
1729
- `info` · `debug` · `trace` all route there; any other `console` method is undefined,
1730
- and CALLING it throws (error text as the value, HTTP 200).
1849
+ - An INLINE body in `xano/` that uses one of these globals does not type-check until that
1850
+ file has `import type {} from "@xano/sdk/lambda-globals"` at the top (safe in the defs
1851
+ program — it is not the frontend); or move the body to a `lam.file` module under
1852
+ `xano/lambdas/`, whose scaffold tsconfig loads the types already.
1853
+ - ⚠ `console` output goes to the request LOG, not stdout. The logging methods (`log` ·
1854
+ `error` · `warn` · `info` · `debug` · `trace`), plus `table` and `dir`, all route there;
1855
+ `group`/`count`/`time`/`assert` are undefined, and CALLING one throws (error text as the
1856
+ value, HTTP 200).
1731
1857
 
1732
1858
  TypeScript annotations survive in the body, and top-level `await` works.
1733
1859
 
1860
+ Inline and `lam.fn` bodies are stored WHITESPACE-MINIFIED on one line, so an error position
1861
+ (`[Line 1:Char 59]`) always says Line 1. Use `lam.file` when you want the body readable or
1862
+ line-accurate errors; its module text is stored as written.
1863
+
1734
1864
  # Lock file
1735
1865
 
1736
1866
  > Read when a `xano.lock` exists or should — renaming/pruning/importing identities, seeding the lock programmatically, or asking which commands write it.
@@ -1739,7 +1869,7 @@ TypeScript annotations survive in the body, and top-level `await` works.
1739
1869
  stay renames (guids otherwise derive from `(type, name)`; a query's from `(api group,
1740
1870
  verb, name)`). Committed. A composed entry is keyed by that identity —
1741
1871
  `query:<group>|<verb>|<name>`, `channel:<server>|<path>`, `message:<server>|<path>|<name>`
1742
- — its guid's seed; a legacy `query:<name>` is migrated by the next locked export.
1872
+ — its guid's seed; a bare `query:<name>` key is rewritten to the composed form by the next locked export.
1743
1873
 
1744
1874
  - `npx @xano/sdk lock rename <kind> <old> <new>` — `kind` is the SDK kind (`table`, `apiGroup`) or stored key (`dbo`).
1745
1875
  Run it when `export` names it after a rename in code (it prints the command); the next export emits the original guid under the new name.
@@ -1755,37 +1885,40 @@ verb, name)`). Committed. A composed entry is keyed by that identity —
1755
1885
  - Programmatic use: call `seedLockOverrides(readLockFile(path))` BEFORE importing any def
1756
1886
  module — references bake guids at import time; `writeBundle` refuses an unseeded lock.
1757
1887
 
1758
- What writes the lock: `export`/`deploy`/`release`/`preflight` of an ENTRY FILE update it;
1759
- `compile`/`paths` only READ. `--no-lock` builds
1760
- without one (names derive guids, the instance invents public URLs, no `--prune`);
1761
- REFUSED over a parseable lock. A DEPLOY or a RELEASE writes back only `landed`: what
1762
- this project LANDED on each destination (ephemerals: `.xano/ephemeral.json`). `--prune` deletes only that — never a merely
1763
- exported name; no record there, no prune until one landing (commit it). A `deploy` (`--replace`
1764
- too) PRESERVES the archive's guids, so the lock still describes the rebuilt
1765
- workspace. CI: `--frozen-lock` fails (`SDK_DRIFT`) instead of changing the lock, and fails while the lock
1766
- carries an entry no exported object matches — a plain `export` only warns and writes that
1767
- entry down, after which nothing tells a rename from a deletion: resolve it with
1768
- `lock rename` or `lock prune`, or accept them with `--allow-lock-orphans` when they are the
1769
- not-yet-ported half of an adopted workspace.
1770
- `export --check` implies `--frozen-lock` and writes nothing — no bundle, no lock — so it
1771
- reads no `xano/.env` or `.secrets.json` and refuses the flags that supply them; this is
1772
- what `npm run xano:check` runs, so CI needs no secrets. With no lock at all, either flag
1773
- fails only when the source has identities to record (an empty workspace passes).
1888
+ ### Writers and readers
1889
+
1890
+ - `export`/`deploy`/`release`/`preflight` of an ENTRY FILE update the lock; `compile`/`routes` only READ.
1891
+ - `--no-lock` builds without one (names derive guids, the instance invents public URLs, no `--prune`);
1892
+ REFUSED over a parseable lock.
1893
+ - A DEPLOY or a RELEASE writes back only `landed`: what this project LANDED on each destination
1894
+ (ephemerals: `.xano/ephemeral.json`). `--prune` deletes only that, never a merely exported name;
1895
+ no record there, no prune until one landing. Commit the lock.
1896
+ - A `deploy` (`--replace` too) PRESERVES the archive's guids, so the lock still describes the rebuilt workspace.
1897
+
1898
+ ### CI
1899
+
1900
+ - `--frozen-lock` fails (`SDK_DRIFT`) instead of changing the lock, and fails while the lock carries
1901
+ an entry no exported object matches. A plain `export` only warns and writes that entry down, after
1902
+ which a rename and a deletion look the same. Resolve it with `lock rename` or `lock prune`, or
1903
+ accept them with `--allow-lock-orphans` when they are the not-yet-ported half of an adopted workspace.
1904
+ - `export --check` implies `--frozen-lock` and writes nothing — no bundle, no lock — so it
1905
+ reads no `xano/.env` or `.secrets.json` and refuses the flags that supply them. `npm run xano:check` runs it,
1906
+ so CI needs no secrets.
1907
+ - With no lock at all, either flag fails only when the source has identities to record (an empty workspace passes).
1774
1908
 
1775
1909
  # Legacy paradigms and retired statements
1776
1910
 
1777
1911
  > Read when the code was PULLED from an existing Xano instance — how a codegen'd tree reads, the shapes in it that must not be "fixed", and any `raw({ name: "mvp:…" })`, `realtimeTrigger()`, or name the catalogs do not list.
1778
1912
 
1779
- Older paradigms this SDK still supports and still emits when it decodes an existing
1780
- workspace. **Do not author these.** They are listed by name only so you recognize them
1913
+ Shapes codegen emits when it decodes an existing workspace, all supported.
1914
+ **Do not author these.** They are listed by name only so you recognize them
1781
1915
  in pulled code rather than "fixing" them; each line names what to use instead.
1782
1916
 
1783
- Names overlap across the split deliberately — the engine reused words like
1784
- "realtime" and "channel" for both generations. A name matching is NOT evidence that
1785
- two things are the same object; check which list it came from.
1917
+ "realtime" and "channel" name objects in both lists: a matching name does NOT mean
1918
+ the same object; check which list it came from.
1786
1919
 
1787
1920
  - `c.expressionLegacy` — the older `const:expr` expression form, emitted by codegen for workspaces that still hold one — author `c.expression` instead.
1788
- - `realtimeTrigger()` — the SUPERSEDED realtime trigger, against the workspace-global realtime layer — a different object from the current `channel`, despite the similar name. For a join hook use `realtimeChannelTrigger({ actions: { join: true } })`; for message handling use a `realtimeMessage()` handler, which is the current equivalent of its `message` action (a message is an authored unit now, not a trigger action).
1921
+ - `realtimeTrigger()` — the SUPERSEDED realtime trigger, against the workspace-global realtime layer — a different object from the current `channel`, despite the similar name. For a join hook use `realtimeChannelTrigger({ actions: { join: true } })`; for message handling use a `realtimeMessage()` handler, which is the equivalent of its `message` action (a message is its own object, not a trigger action).
1789
1922
  - `s.api.realtime_event` — publishes to the SUPERSEDED workspace-global realtime layer, NOT to a `realtimeChannel()` — its `channel` is a string against that layer, so pointing it at a current-layer channel path publishes into the void. Use `s.realtime.publish` instead: it names the owning `realtimeServer()`, so it addresses a real `realtimeChannel()`.
1790
1923
 
1791
1924
  Retired statements and statement VERSIONS — no `s.` surface exists. Pulled code shows
@@ -1805,7 +1938,7 @@ Statements the engine writes but will NOT import back — no `s.` surface exists
1805
1938
  unlike the retired versions above these must be FIXED, not left alone. Pulled code shows
1806
1939
  them as `raw({ name: "…" })`; `export()` refuses any bundle that still contains one.
1807
1940
 
1808
- - `mvp:placeholder` — an unconfigured statement slot the engine writes in place of a statement it could not resolve, so an export stays well-formed. There is no statement class behind it: importing a workspace that contains one fails outright with "Missing statement: mvp:placeholder". Replace it with the statement it stands in for before deploying — there is no destination where it runs.
1941
+ - `mvp:placeholder` — an unconfigured statement slot the engine writes for a statement it could not resolve. Importing a workspace that contains one fails with "Missing statement: mvp:placeholder" on every destination; replace it with the statement it stands in for before deploying.
1809
1942
 
1810
1943
  ## Reading a pulled tree
1811
1944
 
@@ -1827,11 +1960,13 @@ Markers for stored shapes the checks refuse — keep them, not for new code:
1827
1960
 
1828
1961
  > Read for the field signature of a specific statement — every surface, grouped by `s.*` namespace.
1829
1962
 
1963
+ `[special]`: hand-written signature (`llms.txt` Specials, `llms/statements-*`). `[output]`: the engine's output flag; in-place mutators carrying it (`s.math.add`, `bitwise.*`) still take no `as`.
1964
+
1830
1965
  ### (top-level)
1831
1966
 
1832
- `s.throw` raises a named error `s.try_catch` catches; uncaught, it answers HTTP 200 `{ payload, statement: "Throw Error" }` (`s.precondition` sets a status). Inside `s.db.transaction` a throw or failed precondition rolls it back.
1967
+ `s.throw` raises a named error `s.try_catch` catches; uncaught, it answers HTTP 200 `{ payload, statement: "Throw Error" }`, or its `status` (100–599) when it sets one. Inside `s.db.transaction` a throw or failed precondition rolls it back.
1833
1968
 
1834
- - `s.await({ as?: string; ids?: value; timeout?: value })`
1969
+ - `s.await({ as?: string; ids?: value; timeout?: value; terminate?: value })`
1835
1970
  - `s.foreach_break` [special]
1836
1971
  - `s.comment` [special]
1837
1972
  - `s.conditional` [special]
@@ -1841,10 +1976,10 @@ Markers for stored shapes the checks refuse — keep them, not for new code:
1841
1976
  - `s.foreach` [special]
1842
1977
  - `s.group` [special]
1843
1978
  - `s.lambda({ as?: string; code: value; timeout?: value })`
1844
- - `s.precondition({ expr?: comparison; error_type?: "standard" | "notfound" | "toomanyrequests" | "accessdenied" | "unauthorized" | "badrequest" | "inputerror"; error?: value; payload?: value })`
1979
+ - `s.precondition({ expr: comparison; error_type?: "standard" | "notfound" | "toomanyrequests" | "accessdenied" | "unauthorized" | "badrequest" | "inputerror"; error?: value; payload?: value })`
1845
1980
  - `s.return` [special]
1846
1981
  - `s.switch` [special]
1847
- - `s.throw({ name?: string; value: value })`
1982
+ - `s.throw({ name?: string; value: value; status?: number })`
1848
1983
  - `s.try_catch` [special]
1849
1984
  - `s.update_var` [special]
1850
1985
  - `s.set_var` [special]
@@ -1874,23 +2009,25 @@ Markers for stored shapes the checks refuse — keep them, not for new code:
1874
2009
 
1875
2010
  ### array
1876
2011
 
1877
- - `s.array.difference({ as?: string; expr?: value; value?: value; by?: value })`
1878
- - `s.array.every({ expr?: value; as?: string; if?: comparison })` [output] → as: boolean
1879
- - `s.array.filter_count({ expr?: value; as?: string; if?: comparison })`
1880
- - `s.array.filter({ expr?: value; as?: string; if?: comparison })`
1881
- - `s.array.find_index({ expr?: value; as?: string; if?: comparison })`
1882
- - `s.array.find({ expr?: value; as?: string; if?: comparison })` [output]
1883
- - `s.array.group_by({ as?: string; expr?: value; by?: value })`
1884
- - `s.array.has({ expr?: value; as?: string; if?: comparison })`
1885
- - `s.array.intersection({ as?: string; expr?: value; value?: value; by?: value })`
2012
+ `by` is a `$this` expression, NOT a column name: `by: ref("$this.id")` (warns `stack.array-key-constant`). A predicate's `if` binds `$this` only; `$index` only in `partition` (warns `stack.array-index-unbound`).
2013
+
2014
+ - `s.array.difference({ as?: string; expr: value; value: value; by?: value })`
2015
+ - `s.array.every({ expr: value; as?: string; if: comparison })` [output] → as: boolean
2016
+ - `s.array.filter_count({ expr: value; as?: string; if: comparison })`
2017
+ - `s.array.filter({ expr: value; as?: string; if: comparison })`
2018
+ - `s.array.find_index({ expr: value; as?: string; if: comparison })`
2019
+ - `s.array.find({ expr: value; as?: string; if: comparison })` [output]
2020
+ - `s.array.group_by({ as?: string; expr: value; by?: value })`
2021
+ - `s.array.has({ expr: value; as?: string; if: comparison })`
2022
+ - `s.array.intersection({ as?: string; expr: value; value: value; by?: value })`
1886
2023
  - `s.array.map` [special]
1887
- - `s.array.merge({ name?: string; value?: value })` [output]
1888
- - `s.array.partition({ expr?: value; as?: string; if?: comparison })`
1889
- - `s.array.pop({ name?: string; as?: string })` [output]
1890
- - `s.array.push({ name?: string; value: value })` [output]
1891
- - `s.array.shift({ name?: string; as?: string })`
2024
+ - `s.array.merge({ name: string; value: value })` [output]
2025
+ - `s.array.partition({ expr: value; as?: string; if: comparison })`
2026
+ - `s.array.pop({ name: string; as?: string })` [output]
2027
+ - `s.array.push({ name: string; value: value })` [output]
2028
+ - `s.array.shift({ name: string; as?: string })`
1892
2029
  - `s.array.union` [special]
1893
- - `s.array.unshift({ name?: string; value: value })`
2030
+ - `s.array.unshift({ name: string; value: value })`
1894
2031
 
1895
2032
  ### cloud
1896
2033
 
@@ -1958,33 +2095,33 @@ Markers for stored shapes the checks refuse — keep them, not for new code:
1958
2095
 
1959
2096
  ### debug
1960
2097
 
1961
- `s.debug.stop` is a REAL terminator despite the namespace: it ends the request with an error value. Also exported flat as `die()`; there is no `s.die`.
2098
+ `s.debug.stop` is a REAL terminator: it ends the request with HTTP 200 `{ payload, statement: "Stop & Debug" }` (use `s.precondition` for an error status). Also exported flat as `die()`; there is no `s.die`.
1962
2099
 
1963
2100
  - `s.debug.log({ value: value })`
1964
2101
  - `s.debug.stop({ value: value })`
1965
2102
 
1966
2103
  ### expect
1967
2104
 
1968
- Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `.call` bound with `as`. They are NOT inert elsewhere: a failure aborts the stack, so an `s.expect.*` in a `query`/`function`/`task` fails the request with HTTP 500 and the assertion's message (`to_equal failed - expected value 2 does not equal 1`) — remove it. `to_throw` sees only an error carrying a MESSAGE, so an empty-message failure (`ERROR_CODE_ACCESS_DENIED`) reports "response is ok", and `to_be_within` EXCLUDES both bounds — `min < expr < max` — while `s.security.random_number`'s are inclusive.
1969
-
1970
- - `s.expect.to_be_defined({ expr?: value })`
1971
- - `s.expect.to_be_empty({ expr?: value })`
1972
- - `s.expect.to_be_false({ expr?: value })`
1973
- - `s.expect.to_be_greater_than({ expr?: value; value?: value })`
1974
- - `s.expect.to_be_in_the_future({ expr?: value })`
1975
- - `s.expect.to_be_in_the_past({ expr?: value })`
1976
- - `s.expect.to_be_less_than({ expr?: value; value?: value })`
1977
- - `s.expect.to_be_null({ expr?: value })`
1978
- - `s.expect.to_be_true({ expr?: value })`
1979
- - `s.expect.to_be_within({ expr?: value; min?: value; max?: value })`
1980
- - `s.expect.to_contain({ expr?: value; value?: value })`
1981
- - `s.expect.to_end_with({ expr?: value; value?: value })`
1982
- - `s.expect.to_equal({ expr?: value; value?: value })`
1983
- - `s.expect.to_match({ expr?: value; value?: value })`
1984
- - `s.expect.to_not_be_defined({ expr?: value })`
1985
- - `s.expect.to_not_be_null({ expr?: value })`
1986
- - `s.expect.to_not_equal({ expr?: value; value?: value })`
1987
- - `s.expect.to_start_with({ expr?: value; value?: value })`
2105
+ Assertions. Use only in a `workflowTest({...})` stack, asserting on what a `.call` bound with `as`; elsewhere a failure aborts the request with HTTP 500 and the assertion's message (`to_equal failed - expected value 2 does not equal 1`). `to_throw` sees only an error carrying a MESSAGE, so an empty-message failure (`ERROR_CODE_ACCESS_DENIED`) reports "response is ok", and `to_be_within` EXCLUDES both bounds — `min < expr < max`.
2106
+
2107
+ - `s.expect.to_be_defined({ expr: value })`
2108
+ - `s.expect.to_be_empty({ expr: value })`
2109
+ - `s.expect.to_be_false({ expr: value })`
2110
+ - `s.expect.to_be_greater_than({ expr: value; value: value })`
2111
+ - `s.expect.to_be_in_the_future({ expr: value })`
2112
+ - `s.expect.to_be_in_the_past({ expr: value })`
2113
+ - `s.expect.to_be_less_than({ expr: value; value: value })`
2114
+ - `s.expect.to_be_null({ expr: value })`
2115
+ - `s.expect.to_be_true({ expr: value })`
2116
+ - `s.expect.to_be_within({ expr: value; min: value; max: value })`
2117
+ - `s.expect.to_contain({ expr: value; value: value })`
2118
+ - `s.expect.to_end_with({ expr: value; value: value })`
2119
+ - `s.expect.to_equal({ expr: value; value: value })`
2120
+ - `s.expect.to_match({ expr: value; value: value })`
2121
+ - `s.expect.to_not_be_defined({ expr: value })`
2122
+ - `s.expect.to_not_be_null({ expr: value })`
2123
+ - `s.expect.to_not_equal({ expr: value; value: value })`
2124
+ - `s.expect.to_start_with({ expr: value; value: value })`
1988
2125
  - `s.expect.to_throw` [special]
1989
2126
 
1990
2127
  ### function
@@ -1994,14 +2131,14 @@ Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `
1994
2131
 
1995
2132
  ### math
1996
2133
 
1997
- - `s.math.add({ name?: string; value: value })` [output] → as: number
1998
- - `s.math.bitwise.and({ name?: string; value: value })` [output] → as: number
1999
- - `s.math.bitwise.or({ name?: string; value: value })` [output] → as: number
2000
- - `s.math.bitwise.xor({ name?: string; value: value })` [output] → as: number
2001
- - `s.math.div({ name?: string; value: value })`
2002
- - `s.math.mod({ name?: string; value: value })`
2003
- - `s.math.mul({ name?: string; value: value })`
2004
- - `s.math.sub({ name?: string; value: value })`
2134
+ - `s.math.add({ name: string; value: value })` [output]
2135
+ - `s.math.bitwise.and({ name: string; value: value })` [output]
2136
+ - `s.math.bitwise.or({ name: string; value: value })` [output]
2137
+ - `s.math.bitwise.xor({ name: string; value: value })` [output]
2138
+ - `s.math.div({ name: string; value: value })`
2139
+ - `s.math.mod({ name: string; value: value })`
2140
+ - `s.math.mul({ name: string; value: value })`
2141
+ - `s.math.sub({ name: string; value: value })`
2005
2142
 
2006
2143
  ### mcp
2007
2144
 
@@ -2021,14 +2158,15 @@ Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `
2021
2158
 
2022
2159
  ### object
2023
2160
 
2024
- - `s.object.entries({ as?: string; value?: value })` [output] → as: [string, unknown][]
2025
- - `s.object.keys({ as?: string; value?: value })` [output] → as: string[]
2026
- - `s.object.values({ as?: string; value?: value })` [output] → as: unknown[]
2161
+ - `s.object.entries({ as?: string; value: value })` [output] → as: { key: string | number; value: unknown }[] (each entry is a { key, value } OBJECT, NOT a [key, value] tuple; an integer-like key comes back as a number)
2162
+ - `s.object.keys({ as?: string; value: value })` [output] → as: (string | number)[] (an integer-like key comes back as a NUMBER (PHP coerces it), not a string)
2163
+ - `s.object.values({ as?: string; value: value })` [output] → as: unknown[]
2027
2164
 
2028
2165
  ### realtime
2029
2166
 
2030
2167
  - `s.realtime.get_session({ as?: string })`
2031
2168
  - `s.realtime.publish` [special]
2169
+ - `s.realtime.kick` [special]
2032
2170
 
2033
2171
  ### redis
2034
2172
 
@@ -2050,25 +2188,25 @@ Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `
2050
2188
 
2051
2189
  ### security
2052
2190
 
2053
- - `s.security.check_password({ as?: string; text_password: value; hash_password: value })` [output] → as: boolean (true when the plaintext matches the stored hash. ⚠ input.password double-hashes — pass input.text() plaintext)
2191
+ - `s.security.check_password({ as?: string; text_password: value; hash_password: value })` [output] → as: boolean (true when the plaintext matches the stored hash. ⚠ not input.password — pass input.text() plaintext. ⚠ THROWS 500 on a non-hash hash_password (Invalid password syntax.))
2054
2192
  - `s.security.create_auth_token` [special]
2055
2193
  - `s.security.create_curve_key({ as?: string; curve?: "P-256" | "P-384" | "P-521"; format?: "object" | "base64" })`
2056
2194
  - `s.security.create_password({ as?: string; character_count?: value; require_lowercase?: value; require_uppercase?: value; require_digit?: value; require_symbol?: value; symbol_whitelist?: value })`
2057
2195
  - `s.security.create_rsa_key({ as?: string; bits?: value; format?: "object" | "base64" })`
2058
2196
  - `s.security.create_secret_key({ as?: string; bits?: value; format?: "object" | "base64" })`
2059
2197
  - `s.security.create_uuid({ as?: string })`
2060
- - `s.security.decrypt({ as?: string; data: value; algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; key: value; iv: value })`
2198
+ - `s.security.decrypt({ as?: string; data: value; algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; key: value; iv: value })` → as: unknown (the plaintext; takes encrypt's RAW bytes (fl.base64_decode() a stored base64 first). ⚠ THROWS 500 on a wrong key/iv or non-ciphertext — wrap in s.try_catch)
2061
2199
  - `s.security.encrypt({ as?: string; data: value; algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; key: value; iv: value })`
2062
- - `s.security.jwe_decode({ as?: string; token: value; key: value; check_claims?: value; key_algorithm?: "A128KW" | "A192KW" | "A256KW" | "A128GCMKW" | "A192GCMKW" | "A256GCMKW" | "ECDH-ES+A128KW" | "ECDH-ES+A192KW" | "ECDH-ES+A256KW"; content_algorithm?: "A128GCM" | "A192GCM" | "A256GCM" | "A128CBC-HS256" | "A192CBC-HS384" | "A256CBC-HS512"; timeDrift?: value })`
2200
+ - `s.security.jwe_decode({ as?: string; token: value; key: value; check_claims?: value; key_algorithm?: "A128KW" | "A192KW" | "A256KW" | "A128GCMKW" | "A192GCMKW" | "A256GCMKW" | "ECDH-ES+A128KW" | "ECDH-ES+A192KW" | "ECDH-ES+A256KW"; content_algorithm?: "A128GCM" | "A192GCM" | "A256GCM" | "A128CBC-HS256" | "A192CBC-HS384" | "A256CBC-HS512"; timeDrift?: value })` → as: unknown (the decoded claims. ⚠ THROWS 500 ERROR_FATAL on ANY failure (bad/expired token, wrong key/algorithm, failed check_claims) — wrap in s.try_catch for a 401 (statements-calls.md))
2063
2201
  - `s.security.jwe_encode({ as?: string; headers?: value; claims?: value; key: value; key_algorithm?: "A128KW" | "A192KW" | "A256KW" | "A128GCMKW" | "A192GCMKW" | "A256GCMKW" | "ECDH-ES+A128KW" | "ECDH-ES+A192KW" | "ECDH-ES+A256KW"; content_algorithm?: "A128GCM" | "A192GCM" | "A256GCM" | "A128CBC-HS256" | "A192CBC-HS384" | "A256CBC-HS512"; ttl?: value })`
2064
- - `s.security.jws_decode({ as?: string; token: value; key: value; check_claims?: value; signature_algorithm?: "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "HS256" | "HS384" | "HS512" | "ES256" | "ES384" | "ES512"; timeDrift?: value })`
2202
+ - `s.security.jws_decode({ as?: string; token: value; key: value; check_claims?: value; signature_algorithm?: "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "HS256" | "HS384" | "HS512" | "ES256" | "ES384" | "ES512"; timeDrift?: value })` → as: unknown (the decoded claims. ⚠ THROWS 500 ERROR_FATAL on ANY failure (bad/garbage/expired/tampered token, wrong key/signature_algorithm, failed check_claims) — wrap in s.try_catch for a 401 (statements-calls.md))
2065
2203
  - `s.security.jws_encode({ as?: string; headers?: value; claims?: value; key: value; signature_algorithm?: "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "HS256" | "HS384" | "HS512" | "ES256" | "ES384" | "ES512"; ttl?: value })`
2066
- - `s.security.random_bytes({ as?: string; length?: value })`
2204
+ - `s.security.random_bytes({ as?: string; length?: value })` → as: string (RAW bytes (encrypt too) — fl.bin2hex()/fl.base64_encode() before returning or storing; raw binary mangles in a JSON/text response)
2067
2205
  - `s.security.random_number({ as?: string; min?: value; max?: value })`
2068
2206
 
2069
2207
  ### storage
2070
2208
 
2071
- - `s.storage.create_attachment({ as?: string; value: value; access?: "public" | "private" = "public"; filename?: value; include_meta?: boolean; type?: value })`
2209
+ - `s.storage.create_attachment({ as?: string; value: value; access?: "public" | "private" = "public"; filename?: value; include_meta?: boolean; type?: value })` → as: XanoFileRef (the stored file VALUE ({ access, path, name, type, size, mime, meta }) — write it into an f.attachment() cell. ⚠ include_meta: true binds the file's internal RECORD instead (id, guid, sig, the storage BUCKET name): never store it as the file value or return it (warns storage.include-meta-returned). type (also optional) coerces the kind when it is image/video/audio)
2072
2210
  - `s.storage.create_audio({ as?: string; value: value; access?: "public" | "private" = "public"; filename?: value })` [output]
2073
2211
  - `s.storage.create_file_resource({ as?: string; filename: value; filedata: value })` [output]
2074
2212
  - `s.storage.create_image({ as?: string; value: value; access?: "public" | "private" = "public"; filename?: value })` [output]
@@ -2089,17 +2227,19 @@ Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `
2089
2227
 
2090
2228
  ### text
2091
2229
 
2092
- - `s.text.append({ name?: string; value: value })`
2093
- - `s.text.contains({ name?: string; as?: string; value: value })`
2094
- - `s.text.ends_with({ name?: string; as?: string; value: value })`
2095
- - `s.text.icontains({ name?: string; as?: string; value: value })`
2096
- - `s.text.iends_with({ name?: string; as?: string; value: value })`
2097
- - `s.text.istarts_with({ name?: string; as?: string; value: value })`
2098
- - `s.text.ltrim({ name?: string; value: value })`
2099
- - `s.text.prepend({ name?: string; value: value })`
2100
- - `s.text.rtrim({ name?: string; value: value })`
2101
- - `s.text.starts_with({ name?: string; as?: string; value: value })`
2102
- - `s.text.trim({ name?: string; value: value })`
2230
+ `name` is an EXISTING variable the statement acts on. `trim`/`ltrim`/`rtrim`/`append`/`prepend` rewrite it IN PLACE and take no `as` (a non-text var is coerced, a null reads as `""`); on the trims `value` is a SET OF CHARACTERS to strip, not a substring (`"abcHIcba"` trimmed by `"abc"` → `"HI"`). The predicates (`contains`/`icontains`/`starts_with`/`istarts_with`/`ends_with`/`iends_with`) leave `name` unchanged and bind a boolean to `as` — without `as` they compute nothing (warns `stack.predicate-unbound`); an empty or omitted needle is `true`. An undeclared `name` 500s `Missing var entry`.
2231
+
2232
+ - `s.text.append({ name: string; value: value })`
2233
+ - `s.text.contains({ name: string; as?: string; value: value })` → as: boolean
2234
+ - `s.text.ends_with({ name: string; as?: string; value: value })` → as: boolean
2235
+ - `s.text.icontains({ name: string; as?: string; value: value })` → as: boolean
2236
+ - `s.text.iends_with({ name: string; as?: string; value: value })` → as: boolean
2237
+ - `s.text.istarts_with({ name: string; as?: string; value: value })` → as: boolean
2238
+ - `s.text.ltrim({ name: string; value: value })`
2239
+ - `s.text.prepend({ name: string; value: value })`
2240
+ - `s.text.rtrim({ name: string; value: value })`
2241
+ - `s.text.starts_with({ name: string; as?: string; value: value })` → as: boolean
2242
+ - `s.text.trim({ name: string; value: value })`
2103
2243
 
2104
2244
  ### tool
2105
2245
 
@@ -2111,11 +2251,11 @@ Assertions. **Put them in a `workflowTest({...})` stack** — assert on what a `
2111
2251
 
2112
2252
  ### util
2113
2253
 
2114
- `s.util.sleep`'s `value` is in SECONDS; a decimal is allowed (`c.decimal(0.5)` = 500 ms).
2254
+ `s.util.sleep`'s `value` is in SECONDS; a decimal is allowed (`c.decimal(0.5)` = 500 ms); a negative value returns at once. `s.util.set_header`'s `value` is a WHOLE `"Name: value"` line (there is no `name` field) — `c.text("X-Thing: on")`; a line with no colon sends an empty header, and a `Content-Type` line is IGNORED when the response is an object/JSON (it applies to a `c.text()` response). `s.util.template_engine`'s `value` is a Twig template with `$var`/`$input` in scope (`"Hello {{ $var.who }}"`); output is NOT HTML-escaped, a missing var renders `""`, and a syntax error 500s.
2115
2255
 
2116
2256
  - `s.util.geo_distance({ as?: string; latitude_1: value; longitude_1: value; latitude_2: value; longitude_2: value })` → as: number (great-circle distance in METRES (a decimal) — divide by 1000 for km. Identical points return 0)
2117
- - `s.util.get_all_input({ as?: string })` → as: unknown (inside an ATTACHED middleware it is a { type, vars } envelope whose vars DIFFERS BY PHASE: pre → the request inputs; post → { status, result } (plus payload on an error), NOT the request — read the request in post with s.util.get_raw_input. See llms/kinds-core.md)
2118
- - `s.util.get_env({ as?: string })`
2257
+ - `s.util.get_all_input({ as?: string })` → as: unknown (inside an ATTACHED middleware it is a { type, vars } envelope whose vars DIFFERS BY PHASE: pre → the request inputs; post → { status, result }, NOT the request — read the request in post with s.util.get_raw_input. ⚠ status is the STRING "ok" | "exception" (NOT an HTTP code), so store it in a text column, not f.int(); on "exception", result is the { code, message, payload } error and payload is set. See llms/kinds-core.md)
2258
+ - `s.util.get_env({ as?: string })` → as: Record<string, string> (every workspace env var (declared AND dashboard) as one { NAME: value } object, each value TEXT — so this binds every SECRET; never return it to a client or write it to a row)
2119
2259
  - `s.util.get_input` [special]
2120
2260
  - `s.util.get_raw_input` [special]
2121
2261
  - `s.util.get_vars({ as?: string })`