tenjin-cli 0.1.0-alpha.31 → 0.1.0-alpha.32

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 (258) hide show
  1. package/README.md +5 -5
  2. package/dist/{_esm-MEXZI5DL.js → _esm-RLLC72MS.js} +128 -132
  3. package/dist/{alive-J64H46HI.js → alive-MROUMFH3.js} +13 -6
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3AIHRXKO.js +72 -0
  11. package/dist/chunk-3AIHRXKO.js.map +1 -0
  12. package/dist/{chunk-LEFIX6RS.js → chunk-3DIL66VX.js} +31 -11
  13. package/dist/chunk-3DIL66VX.js.map +1 -0
  14. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  15. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  16. package/dist/{chunk-7Q5FDF65.js → chunk-445VQTVM.js} +3 -3
  17. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  18. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  19. package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
  20. package/dist/chunk-62KNUYWD.js +111 -0
  21. package/dist/chunk-62KNUYWD.js.map +1 -0
  22. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  23. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  24. package/dist/{chunk-5MARFNSB.js → chunk-AD226HDR.js} +49 -30
  25. package/dist/chunk-AD226HDR.js.map +1 -0
  26. package/dist/chunk-ADV4LDTB.js +106 -0
  27. package/dist/chunk-ADV4LDTB.js.map +1 -0
  28. package/dist/{chunk-7WU4OPLP.js → chunk-AV5NZMYO.js} +5 -3
  29. package/dist/{chunk-7WU4OPLP.js.map → chunk-AV5NZMYO.js.map} +1 -1
  30. package/dist/chunk-B7EM4GGF.js +198 -0
  31. package/dist/chunk-B7EM4GGF.js.map +1 -0
  32. package/dist/chunk-BFDQ4WNW.js +119 -0
  33. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  34. package/dist/{chunk-2XLC3AEX.js → chunk-BI673VEJ.js} +536 -510
  35. package/dist/chunk-BI673VEJ.js.map +1 -0
  36. package/dist/chunk-CEXSOI5R.js +808 -0
  37. package/dist/chunk-CEXSOI5R.js.map +1 -0
  38. package/dist/{chunk-FW75G2W4.js → chunk-CISYM4EO.js} +5 -5
  39. package/dist/{chunk-B7HUUJOK.js → chunk-D3ZURCG7.js} +3 -3
  40. package/dist/chunk-D5TOQSO4.js +474 -0
  41. package/dist/chunk-D5TOQSO4.js.map +1 -0
  42. package/dist/{chunk-UQUOVWBG.js → chunk-DRDUIZIA.js} +7 -7
  43. package/dist/{chunk-27EPWVOY.js → chunk-DW4YTVR3.js} +2 -2
  44. package/dist/chunk-E7LGOMH6.js +449 -0
  45. package/dist/chunk-E7LGOMH6.js.map +1 -0
  46. package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
  47. package/dist/chunk-E7SW44LM.js.map +1 -0
  48. package/dist/chunk-EDJWHDDL.js +33 -0
  49. package/dist/chunk-EDJWHDDL.js.map +1 -0
  50. package/dist/chunk-F3ED5WTR.js +13 -0
  51. package/dist/chunk-F3ED5WTR.js.map +1 -0
  52. package/dist/chunk-G75OPGAK.js +111 -0
  53. package/dist/chunk-G75OPGAK.js.map +1 -0
  54. package/dist/{chunk-R5LCN54M.js → chunk-GAKUQHKA.js} +13 -17
  55. package/dist/{chunk-R5LCN54M.js.map → chunk-GAKUQHKA.js.map} +1 -1
  56. package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
  57. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  58. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  59. package/dist/{chunk-6E5R45ZO.js → chunk-HREHWL32.js} +4 -4
  60. package/dist/{chunk-6E5R45ZO.js.map → chunk-HREHWL32.js.map} +1 -1
  61. package/dist/{chunk-KXVP2VKA.js → chunk-I5TDIUKM.js} +15 -34
  62. package/dist/chunk-I5TDIUKM.js.map +1 -0
  63. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  64. package/dist/chunk-IADZOXKN.js.map +1 -0
  65. package/dist/{chunk-P4NH7OUK.js → chunk-IDTRSAHE.js} +2 -2
  66. package/dist/{chunk-YFPY4ONH.js → chunk-JEVQ5LKO.js} +4 -4
  67. package/dist/chunk-JNJWBTU2.js +3497 -0
  68. package/dist/chunk-JNJWBTU2.js.map +1 -0
  69. package/dist/{chunk-MNXS2U45.js → chunk-JRZBBPO6.js} +167 -86
  70. package/dist/chunk-JRZBBPO6.js.map +1 -0
  71. package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
  72. package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
  73. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  74. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  75. package/dist/{chunk-AGZ7PJKY.js → chunk-OTWLERSW.js} +22 -5
  76. package/dist/chunk-OTWLERSW.js.map +1 -0
  77. package/dist/{chunk-NEFNKLBE.js → chunk-PJNENX2A.js} +1535 -422
  78. package/dist/chunk-PJNENX2A.js.map +1 -0
  79. package/dist/{chunk-UKY4CHNC.js → chunk-PKHI276N.js} +8 -4
  80. package/dist/chunk-PKHI276N.js.map +1 -0
  81. package/dist/{chunk-5K5W4S66.js → chunk-QF3LSMGS.js} +2 -2
  82. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  83. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  84. package/dist/{chunk-OHRR5OYM.js → chunk-SFASB5FL.js} +10 -4
  85. package/dist/chunk-SFASB5FL.js.map +1 -0
  86. package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
  87. package/dist/chunk-SNNSAGMT.js.map +1 -0
  88. package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
  89. package/dist/chunk-SYOS5CAC.js +176 -0
  90. package/dist/chunk-SYOS5CAC.js.map +1 -0
  91. package/dist/chunk-TAW4UFFF.js +293 -0
  92. package/dist/chunk-TAW4UFFF.js.map +1 -0
  93. package/dist/{hosts-FWZOV26H.js → chunk-TF5HCP33.js} +79 -24
  94. package/dist/chunk-TF5HCP33.js.map +1 -0
  95. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  96. package/dist/chunk-UUGOUOVT.js.map +1 -0
  97. package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
  98. package/dist/{chunk-K72RURN3.js → chunk-VJUVFZ2D.js} +2 -2
  99. package/dist/{chunk-77TCKDEC.js → chunk-VOZA6O7K.js} +663 -477
  100. package/dist/chunk-VOZA6O7K.js.map +1 -0
  101. package/dist/{chunk-D65GNPS3.js → chunk-VUGQTZ2L.js} +208 -84
  102. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  103. package/dist/chunk-WOM257PW.js +393 -0
  104. package/dist/chunk-WOM257PW.js.map +1 -0
  105. package/dist/chunk-WYXUQGOL.js +191 -0
  106. package/dist/chunk-WYXUQGOL.js.map +1 -0
  107. package/dist/chunk-X5ZBP3IY.js +97 -0
  108. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  109. package/dist/{chunk-5C32RLTA.js → chunk-YUY4SAGM.js} +17 -2
  110. package/dist/chunk-YUY4SAGM.js.map +1 -0
  111. package/dist/{cli-D5OE3URZ.js → cli-FB4LOA5A.js} +144 -63
  112. package/dist/{cli-D5OE3URZ.js.map → cli-FB4LOA5A.js.map} +1 -1
  113. package/dist/{codex-event-PPNVRRDH.js → codex-event-TYVES3UX.js} +2 -2
  114. package/dist/{codex-host-2RJOJW2B.js → codex-host-WW4H2SKT.js} +7 -6
  115. package/dist/codex-install-2C623HPW.js +393 -0
  116. package/dist/codex-install-2C623HPW.js.map +1 -0
  117. package/dist/{config-ZD4OB2DO.js → config-HOVJFEKD.js} +21 -17
  118. package/dist/doctor-NKU4V5OV.js +1312 -0
  119. package/dist/doctor-NKU4V5OV.js.map +1 -0
  120. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  121. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  122. package/dist/{fund-5ITKQGYF.js → fund-WEBHTZGN.js} +37 -36
  123. package/dist/{fund-5ITKQGYF.js.map → fund-WEBHTZGN.js.map} +1 -1
  124. package/dist/hook-command-ZA2PNKS6.js +44 -0
  125. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  126. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  127. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  128. package/dist/hosts/codex/tenjin/.mcp.json +3 -0
  129. package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
  130. package/dist/hosts-AV5MHBAU.js +38 -0
  131. package/dist/index.js +28 -8
  132. package/dist/index.js.map +1 -1
  133. package/dist/{install-XWGE4Q7L.js → install-PT4EZS4R.js} +53 -30
  134. package/dist/{install-identity-K7EJIQFP.js → install-identity-5A4OE6YC.js} +11 -10
  135. package/dist/install-wallet-SAAPKB73.js +281 -0
  136. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  137. package/dist/{mcp-3LIJSSJB.js → mcp-HAWKCTPQ.js} +785 -210
  138. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  139. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  140. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  141. package/dist/{package-ZKQFDWLE.js → package-SR2WB6MK.js} +4 -2
  142. package/dist/passphrase-IFTDS3CU.js +44 -0
  143. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  144. package/dist/{pay-WHBERZ3W.js → pay-OXC3WKYV.js} +29 -29
  145. package/dist/{payments-KVICEKD2.js → payments-3KHMP2MG.js} +15 -14
  146. package/dist/{payments-KVICEKD2.js.map → payments-3KHMP2MG.js.map} +1 -1
  147. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  148. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  149. package/dist/runtime-UVNUA3AS.js +1203 -0
  150. package/dist/runtime-UVNUA3AS.js.map +1 -0
  151. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  152. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  153. package/dist/{send-7G7Y7DLN.js → send-HMKJLT34.js} +24 -22
  154. package/dist/{send-7G7Y7DLN.js.map → send-HMKJLT34.js.map} +1 -1
  155. package/dist/{status-OF7RH5HM.js → status-RWXIIWYS.js} +55 -25
  156. package/dist/status-RWXIIWYS.js.map +1 -0
  157. package/dist/{status-line-XOUE6MPL.js → status-line-77XYZP7E.js} +10 -9
  158. package/dist/{status-line-XOUE6MPL.js.map → status-line-77XYZP7E.js.map} +1 -1
  159. package/dist/uninstall-D5G67UJH.js +480 -0
  160. package/dist/uninstall-D5G67UJH.js.map +1 -0
  161. package/dist/update-LRNOEGSB.js +53 -0
  162. package/dist/update-LRNOEGSB.js.map +1 -0
  163. package/dist/{usdc-OGOGEHV2.js → usdc-D6X7EIQ2.js} +6 -8
  164. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  165. package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  166. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  167. package/dist/wallet-XFYC27BR.js +55 -0
  168. package/dist/wallet-XFYC27BR.js.map +1 -0
  169. package/dist/wallet-kdf-worker.mjs +8 -8
  170. package/docs/agent-permissions.md +40 -22
  171. package/docs/safety-model.md +1 -1
  172. package/docs/troubleshooting.md +72 -1
  173. package/package.json +14 -1
  174. package/dist/ccip-NLCSCHKI.js +0 -19
  175. package/dist/chunk-2XLC3AEX.js.map +0 -1
  176. package/dist/chunk-4ZZO6ULA.js.map +0 -1
  177. package/dist/chunk-5C32RLTA.js.map +0 -1
  178. package/dist/chunk-5IEP5EGE.js +0 -5332
  179. package/dist/chunk-5IEP5EGE.js.map +0 -1
  180. package/dist/chunk-5MARFNSB.js.map +0 -1
  181. package/dist/chunk-77TCKDEC.js.map +0 -1
  182. package/dist/chunk-7EKYXMUO.js +0 -7536
  183. package/dist/chunk-7EKYXMUO.js.map +0 -1
  184. package/dist/chunk-7QKHZQKW.js.map +0 -1
  185. package/dist/chunk-AGZ7PJKY.js.map +0 -1
  186. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  187. package/dist/chunk-BL3332HQ.js +0 -7611
  188. package/dist/chunk-BL3332HQ.js.map +0 -1
  189. package/dist/chunk-D65GNPS3.js.map +0 -1
  190. package/dist/chunk-EGELTSPU.js +0 -2865
  191. package/dist/chunk-EGELTSPU.js.map +0 -1
  192. package/dist/chunk-GA7JETVM.js +0 -150
  193. package/dist/chunk-GA7JETVM.js.map +0 -1
  194. package/dist/chunk-I3EQFHCD.js +0 -175
  195. package/dist/chunk-I3EQFHCD.js.map +0 -1
  196. package/dist/chunk-K3I7C2MO.js +0 -1185
  197. package/dist/chunk-K3I7C2MO.js.map +0 -1
  198. package/dist/chunk-KXVP2VKA.js.map +0 -1
  199. package/dist/chunk-LEFIX6RS.js.map +0 -1
  200. package/dist/chunk-MNXS2U45.js.map +0 -1
  201. package/dist/chunk-NEFNKLBE.js.map +0 -1
  202. package/dist/chunk-OHRR5OYM.js.map +0 -1
  203. package/dist/chunk-QSCPK4F5.js.map +0 -1
  204. package/dist/chunk-SJLTEINJ.js.map +0 -1
  205. package/dist/chunk-TTNESUPQ.js.map +0 -1
  206. package/dist/chunk-UKY4CHNC.js.map +0 -1
  207. package/dist/chunk-V6BSF6OC.js +0 -260
  208. package/dist/chunk-V6BSF6OC.js.map +0 -1
  209. package/dist/chunk-YVFXE7RR.js.map +0 -1
  210. package/dist/codex-install-UUZ6QMBQ.js +0 -221
  211. package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
  212. package/dist/doctor-KBR34Q4B.js +0 -601
  213. package/dist/doctor-KBR34Q4B.js.map +0 -1
  214. package/dist/hook-command-4TYCHHRL.js +0 -39
  215. package/dist/hosts-FWZOV26H.js.map +0 -1
  216. package/dist/install-wallet-XQ6XFZV4.js +0 -117
  217. package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
  218. package/dist/mcp-3LIJSSJB.js.map +0 -1
  219. package/dist/plugin-registration-5TIA564H.js +0 -54
  220. package/dist/status-OF7RH5HM.js.map +0 -1
  221. package/dist/uninstall-JXUAFNDB.js +0 -158
  222. package/dist/uninstall-JXUAFNDB.js.map +0 -1
  223. package/dist/update-ZKUERSO2.js +0 -44
  224. package/dist/wallet-2HA6W4R4.js +0 -43
  225. /package/dist/{_esm-MEXZI5DL.js.map → _esm-RLLC72MS.js.map} +0 -0
  226. /package/dist/{alive-J64H46HI.js.map → alive-MROUMFH3.js.map} +0 -0
  227. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  228. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  229. /package/dist/{chunk-7Q5FDF65.js.map → chunk-445VQTVM.js.map} +0 -0
  230. /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
  231. /package/dist/{chunk-FW75G2W4.js.map → chunk-CISYM4EO.js.map} +0 -0
  232. /package/dist/{chunk-B7HUUJOK.js.map → chunk-D3ZURCG7.js.map} +0 -0
  233. /package/dist/{chunk-UQUOVWBG.js.map → chunk-DRDUIZIA.js.map} +0 -0
  234. /package/dist/{chunk-27EPWVOY.js.map → chunk-DW4YTVR3.js.map} +0 -0
  235. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  236. /package/dist/{chunk-P4NH7OUK.js.map → chunk-IDTRSAHE.js.map} +0 -0
  237. /package/dist/{chunk-YFPY4ONH.js.map → chunk-JEVQ5LKO.js.map} +0 -0
  238. /package/dist/{chunk-5K5W4S66.js.map → chunk-QF3LSMGS.js.map} +0 -0
  239. /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
  240. /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
  241. /package/dist/{chunk-K72RURN3.js.map → chunk-VJUVFZ2D.js.map} +0 -0
  242. /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-TYVES3UX.js.map} +0 -0
  243. /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  244. /package/dist/{config-ZD4OB2DO.js.map → config-HOVJFEKD.js.map} +0 -0
  245. /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  246. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  247. /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  248. /package/dist/{install-XWGE4Q7L.js.map → hosts-AV5MHBAU.js.map} +0 -0
  249. /package/dist/{install-identity-K7EJIQFP.js.map → install-PT4EZS4R.js.map} +0 -0
  250. /package/dist/{package-ZKQFDWLE.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  251. /package/dist/{paths-POPTXJO6.js.map → package-SR2WB6MK.js.map} +0 -0
  252. /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  253. /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
  254. /package/dist/{redact-6W23GGJC.js.map → pay-OXC3WKYV.js.map} +0 -0
  255. /package/dist/{update-ZKUERSO2.js.map → plugin-registration-N3GRIZVM.js.map} +0 -0
  256. /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
  257. /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-EKFRNR6Z.js.map} +0 -0
  258. /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-BDWZG2TQ.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/config.ts","../src/lib/harness-permissions.ts","../src/lib/codex-rules.ts","../src/lib/skill-wiring.ts","../src/lib/skills-source.ts","../src/adapters/claude.ts","../src/adapters/codex.ts","../src/lib/codex-trust.ts","../src/adapters/registry.ts","../src/lib/harness-hooks.ts","../src/lib/harness-presence.ts","../src/router/spend-question.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport type { CodexGrantResult } from '../lib/harness-permissions';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from '../lib/production-origin';\nimport {\n CONFIG_KEYS,\n RETIRED_PAYMENT_GUIDANCE,\n retiredPaymentKeys,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n LOOP_CONFIG_KEYS,\n TEAM_CONFIG_KEYS,\n EXPERIMENTAL_CONFIG_KEYS,\n ROUTER_CONFIG_KEYS,\n ROUTER_CONTEXTS,\n loadRawConfig,\n MAX_AUTO_SPEND_FLOOR_ATOMIC,\n MAX_AUTO_SPEND_FLOOR_WHY,\n parseLoopValue,\n parsePublicFallbackFlag,\n parseAckServerWarnings,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HookArm,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n UpdateConfigKey,\n LoopConfigKey,\n TeamConfigKey,\n ExperimentalConfigKey,\n RouterConfigKey,\n RouterContext,\n} from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { Harness, HarnessAdapter } from '../adapters/types';\nimport { ADAPTERS } from '../adapters/registry';\nimport { isTeamShelfOrigin, loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { installedHarnessInPlay } from '../lib/harness-presence';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\nimport { ROUTER_DEFAULTS, type RouterLimits } from '../router/spend-question';\nimport {\n projectRouterPath,\n readProjectRouterFile,\n routerSettings,\n type RouterSettings,\n} from '../router/settings';\nimport { style } from '../lib/output';\n\n/** Machine values use Money for spending keys and scalars for other settings. */\ninterface RenderedValue {\n value: Money | string | string[] | boolean | null;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n /** The file a router key came from, when one did. */\n path?: string;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Harness lifecycle implementations; tests inject adapters at this boundary. */\n adapters?: Readonly<Record<Harness, HarnessAdapter>>;\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Settled harness selection; absent, each registered adapter is detected normally. */\n harnessesInPlay?: readonly Harness[];\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\n/**\n * The shelf's settings. `config get/set` still accept them and `--json` still\n * carries them, but the human listing shows only what the router CLI uses: it\n * ships no shelf command that reads these.\n */\nconst SHELF_KEYS: ReadonlySet<string> = new Set<string>([\n 'allowlistCreators',\n 'publicShelfUrl',\n 'shelfBypassSecret',\n 'evalCohort',\n ...PUBLISH_CONFIG_KEYS,\n ...HOOKS_CONFIG_KEYS,\n ...LOOP_CONFIG_KEYS,\n ...TEAM_CONFIG_KEYS,\n]);\n\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...UPDATE_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS]\n .filter((key) => !SHELF_KEYS.has(key))\n .map((key) => key.length),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend:\n 'automatic router limit per call, the runaway guard: at least 0.25 (the default); router.enabled false turns the router off',\n sessionBudget:\n 'automatic router daily limit, the main control (5 by default): 0 blocks automatic spend, none removes the ceiling',\n sendMaxAmount:\n 'hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL the router asks',\n publicShelfUrl:\n 'the public marketplace, consume-only: the second shelf a team-mode search falls through to',\n shelfBypassSecret:\n \"the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)\",\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n bazaarRegistries: 'x402 registries used to verify direct-payment listings',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'publish.ackServerWarnings':\n \"whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never\",\n 'hooks.prompt': 'answer the prompt you just typed with what the shelves already know',\n 'hooks.web-search': 'ask Tenjin before the agent runs a WebSearch',\n 'hooks.web-fetch': 'ask Tenjin before the agent fetches a page',\n 'hooks.subagent':\n 'ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start',\n 'hooks.failure': 'answer a failing command with the fix this machine or a shelf already has',\n 'hooks.publish':\n 'the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end',\n 'hooks.primer': 'one-paragraph search-first primer at session start',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n 'loop.human_wait_ms':\n 'ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)',\n 'loop.tool_wait_ms': 'ms a hook fire may take when a tool call is waiting on it',\n 'loop.idle_exit_min': 'minutes without a hook fire before the loop daemon exits',\n 'loop.port':\n \"the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)\",\n 'team.publicFallback':\n 'on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)',\n 'router.enabled':\n 'false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it',\n 'router.context':\n 'session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled',\n 'experimental.bazaar':\n \"EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only\",\n};\n\n/**\n * What turning the experimental list on means, said when it is turned on:\n * whose services these are, that the price is theirs, and how to turn it off.\n */\nexport const EXPERIMENTAL_BAZAAR_WARNING =\n \"Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. \" +\n 'They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, ' +\n 'prices can vary with the input, and payments are real, under your spend limits. ' +\n \"To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. \" +\n \"Tenjin's reviewed list stays on either way. Turn this off with \" +\n '`tenjin config set experimental.bazaar off`.';\n\nfunction isExperimentalKey(key: string): key is ExperimentalConfigKey {\n return (EXPERIMENTAL_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isLoopKey(key: string): key is LoopConfigKey {\n return (LOOP_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isTeamKey(key: string): key is TeamConfigKey {\n return (TEAM_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isRouterKey(key: string): key is RouterConfigKey {\n return (ROUTER_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/** The list/get shape for a router key, with the file that set it. */\nfunction renderRouterSetting(key: RouterConfigKey, settings: RouterSettings): RenderedSetting {\n const { value, source, path } = key === 'router.enabled' ? settings.enabled : settings.context;\n return { value, source, ...(path !== undefined ? { path } : {}) };\n}\n\n/** Router keys resolve against the directory the command runs in, as a hook would. */\nasync function resolveRouterFromContext(ctx: CommandContext): Promise<RouterSettings> {\n return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });\n}\n\nfunction renderLoopSetting(key: LoopConfigKey, settings: EffectiveSettings): RenderedSetting {\n const field = key.slice('loop.'.length) as keyof EffectiveSettings['loop'];\n const { value, source } = settings.loop[field];\n return { value: value === null ? 'null' : String(value), source };\n}\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n const show = (key: string, line: string) => {\n if (!SHELF_KEYS.has(key)) humanLines.push(line);\n };\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of LOOP_CONFIG_KEYS) {\n const entry = renderLoopSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of TEAM_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.teamPublicFallback.value,\n source: settings.teamPublicFallback.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n const router = await resolveRouterFromContext(ctx);\n for (const key of ROUTER_CONFIG_KEYS) {\n const entry = renderRouterSetting(key, router);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of EXPERIMENTAL_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.experimentalBazaar.value,\n source: settings.experimentalBazaar.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isLoopKey(key)) {\n const entry = renderLoopSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isTeamKey(key)) {\n const { teamPublicFallback } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: teamPublicFallback.value,\n source: teamPublicFallback.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isRouterKey(key)) {\n const entry = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isExperimentalKey(key)) {\n const { experimentalBazaar } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: experimentalBazaar.value,\n source: experimentalBazaar.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n {\n key,\n value,\n project,\n local,\n }: { key: string; value: string; project?: boolean; local?: boolean },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (local === true && project !== true) {\n throw new CliError('USAGE', '--local names the personal project file, so it needs --project', {\n fix: `Run \\`tenjin config set --project --local ${key} ${value}\\`.`,\n });\n }\n if (isRouterKey(key)) {\n return setRouterKey(key, value, ctx, project === true ? { local: local === true } : undefined);\n }\n if (project === true) {\n throw new CliError('USAGE', `${key} is not a project key`, {\n fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(' and ')} only; drop it to set ${key} for this machine.`,\n });\n }\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n if (isLoopKey(key)) return setLoopKey(key, value, ctx);\n if (isTeamKey(key)) return setTeamKey(key, value, ctx);\n if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);\n return {\n data: { key: configKey, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(configKey, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * The half-wired team shelf, said out loud at the moment it is created.\n *\n * Team mode takes TWO settings — a private deployment in `baseUrl` and its\n * bypass secret — and the setup is two independent commands, so a machine can\n * easily end up with the secret and no shelf (run in the other order, or the\n * secret line alone on a second machine). The CLI fails that state safe to\n * public mode, which means an operator who thinks they are on the team shelf\n * would otherwise get no signal at all: publishes would go to the marketplace\n * under the public gates. Warn, do not refuse — the pair is legitimately\n * half-set between two commands, and refusing would make the documented order\n * the only order.\n *\n * THREE KEYS, not two. `isTeamShelfOrigin` also returns false when `baseUrl`\n * matches `publicShelfUrl`, so pointing `publicShelfUrl` at the team deployment\n * drops the machine out of team mode just as surely as unsetting the secret\n * would. It fails safe and doctor catches it later; this is the warning at the\n * moment it happens, on the third key of the same triple.\n */\nasync function halfWiredTeamShelf(\n configKey: ScalarConfigKey,\n dataDir: string,\n): Promise<string | undefined> {\n if (\n configKey !== 'shelfBypassSecret' &&\n configKey !== 'baseUrl' &&\n configKey !== 'publicShelfUrl'\n ) {\n return undefined;\n }\n const config = await loadRawConfig(dataDir).catch(() => undefined);\n if (config === undefined) return undefined;\n const s = resolveSettings({ config, flags: {}, env: {} });\n if (s.shelfBypassSecret.value.length === 0) return undefined;\n const baseUrl = s.baseUrl.value;\n if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return undefined;\n // WHICH KEY BROKE THE PAIR decides which fix to name. A baseUrl that now\n // matches publicShelfUrl is not \"the marketplace\" in any recognizable sense —\n // it is the operator's own two keys pointed at one place — and telling them to\n // re-point baseUrl would be advice for the other half of the same collision.\n const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);\n const cause = isProduction\n ? `baseUrl is the public marketplace (${baseUrl})`\n : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;\n const fix = isProduction\n ? 'Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`.'\n : `A team shelf must differ from the shelf it falls through to: \\`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\\`.`;\n return (\n `Warning: shelfBypassSecret is set, but ${cause}, ` +\n 'so this machine stays in PUBLIC mode — publishes go to the marketplace with the scan’s ' +\n 'warn tier and the confirm cascade on. ' +\n fix\n );\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice|publish.ackServerWarnings`. mode\n * and ackServerWarnings validate to their enums; defaultPrice parses decimal USD\n * at the edge into atomic (matching the spend keys). The subkey is merged into\n * the nested publish block, so a sibling subkey (or an unknown one a newer CLI\n * wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : key === 'publish.ackServerWarnings'\n ? { value: parseAckServerWarnings(value, key), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey =\n key === 'publish.mode'\n ? 'mode'\n : key === 'publish.ackServerWarnings'\n ? 'ackServerWarnings'\n : 'defaultPrice';\n const stored =\n key === 'publish.defaultPrice' ? (entry.value as Money).atomic : (entry.value as string);\n const persistEntry = async (): Promise<void> =>\n persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') {\n await persistEntry();\n return { data: { key, ...entry }, humanLines };\n }\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n // Synchronize before committing the mode. A grant writer may refuse after\n // consent (permissions, concurrent edits, an unwritable parent); persisting\n // first made the command exit successfully with an unattended mode that its\n // harness could not carry. Grant-first is also the least-authority failure\n // order: if a later config write fails, the CLI still resolves the old mode.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n const failure = grantSyncFailure(allowlist);\n if (failure !== undefined) {\n throw new CliError(\n 'REFUSED',\n `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,\n {\n fix:\n failure.fix ??\n `Fix the permissions for ${failure.path}, then re-run \\`tenjin config set publish.mode ${entry.value as string}\\`.`,\n details: { key, value: entry.value, allowlist },\n },\n );\n }\n await persistEntry();\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n byHarness: Partial<Record<Harness, PermissionsResult | CodexGrantResult>>;\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** A writer refusal is an error, not informational output: the mode and every\n * harness grant are one operator decision and may not report success apart. */\nfunction grantSyncFailure(\n sync: AllowlistSync,\n): { harness: Harness; path: string; reason: string; fix?: string } | undefined {\n for (const [harness, result] of Object.entries(sync.byHarness) as [\n Harness,\n PermissionsResult | CodexGrantResult,\n ][]) {\n if ('error' in result && result.error !== undefined) {\n return { harness, path: result.path, reason: result.error };\n }\n if ('warning' in result && result.warning !== undefined) {\n return {\n harness,\n path: result.path ?? '(unknown path)',\n reason: result.warning,\n ...(result.fix !== undefined ? { fix: result.fix } : {}),\n };\n }\n }\n return undefined;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(\n mode: PublishMode,\n pending: readonly string[],\n harnesses: readonly Harness[],\n): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} command-grant rule(s) \\`tenjin install\\` writes.` : '';\n const targets = harnesses\n .map((harness) =>\n harness === 'claude' ? 'Claude Code' : harness === 'codex' ? 'Codex' : harness,\n )\n .join(' and ');\n return (\n `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ` +\n `${MODE_GATED_RULES.join(' and ')}. Update the ${targets} grant now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { byHarness: {} };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n byHarness: { claude: result },\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { byHarness: { claude: result } };\n };\n\n const adapters = deps.adapters ?? ADAPTERS;\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((config) => config.install?.harness ?? [])\n .catch(() => [] as Harness[]);\n const inPlay =\n deps.harnessesInPlay ??\n (\n await Promise.all(\n Object.values(adapters).map(async (adapter) => ({\n adapter,\n selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {\n env,\n which,\n requested,\n }),\n })),\n )\n )\n .filter((entry) => entry.selected)\n .map((entry) => entry.adapter.id);\n const selectedAdapters = inPlay.map((harness) => adapters[harness]);\n const isClaude = inPlay.includes('claude');\n\n const withOtherGrants = async (sync: AllowlistSync): Promise<AllowlistSync> => {\n const byHarness = { ...sync.byHarness };\n for (const adapter of selectedAdapters) {\n if (adapter.id === 'claude' || adapter.registrar.grant === undefined) continue;\n const result = await adapter.registrar.grant.write(home, mode, env);\n byHarness[adapter.id] = result;\n }\n return { ...sync, byHarness };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n if (selectedAdapters.every((adapter) => adapter.registrar.grant === undefined)) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = isClaude\n ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode)\n : { pending: [] as string[] };\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = isClaude\n ? await (deps.retractModeGated ?? retractModeGatedRules)(home)\n : undefined;\n if (retracted?.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return await withOtherGrants({\n byHarness: retracted === undefined ? {} : { claude: retracted },\n });\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined && selectedAdapters.length === 1 && isClaude) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) {\n return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n }\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n const grantable = selectedAdapters\n .filter((adapter) => adapter.registrar.grant !== undefined)\n .map((adapter) => adapter.id);\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable)))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return await withOtherGrants(isClaude ? await write() : nothing);\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n const claude = sync.byHarness.claude as PermissionsResult | undefined;\n if ((claude?.added.length ?? 0) > 0) {\n lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);\n }\n if ((claude?.removed.length ?? 0) > 0) {\n lines.push(`Removed ${claude?.removed.join(', ')} from your allowlist.`);\n }\n const grant = sync.byHarness.codex as CodexGrantResult | undefined;\n if (grant !== undefined && grant.error === undefined && grant.wrote) {\n lines.push(\n `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`,\n );\n }\n if (grant?.error !== undefined) {\n lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.<arm>`. Merged into the nested hooks block through the same\n * locked read-modify-write every other set uses, so a subkey a newer CLI wrote\n * survives. The daemon re-stats this file per fire, so every value takes effect\n * on the next prompt with no re-install and no process to restart.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const arm = key.slice('hooks.'.length) as HookArm;\n const parsed = parseBoolean(value);\n await persistHookArm(ctx.dataDir, arm, parsed);\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // NO STALENESS WARNING, and there is nothing left to warn about: every hooks\n // key is read out of `config.json` by the daemon on each fire, so a value set\n // here takes effect on the next prompt with nothing to re-install.\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set loop.*` and `config set team.publicFallback`. The daemon stats\n * `config.json` per fire and reloads on an mtime change, so a set takes effect\n * on the next hook fire with no restart (02-redesign.md §4a).\n */\nasync function setLoopKey(\n key: LoopConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseLoopValue(key, value);\n const field = key.slice('loop.'.length);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n loop: { ...existing.loop, [field]: parsed },\n }));\n const entry: RenderedSetting = {\n value: parsed === null ? 'null' : String(parsed),\n source: 'file',\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nasync function setTeamKey(\n key: TeamConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n team: { ...existing.team, publicFallback: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/** `config set experimental.bazaar on|off`; turning it on says what it means. */\nasync function setExperimentalKey(\n key: ExperimentalConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n experimental: { ...existing.experimental, bazaar: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n const warning = parsed === 'on' ? EXPERIMENTAL_BAZAAR_WARNING : undefined;\n return {\n data: { key, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(key, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * `config set [--project [--local]] router.enabled|router.context`. Without\n * `--project` the key goes into the global config through the same locked merge\n * every set uses. With it, into the project file {@link projectRouterPath}\n * names from here, merged so a sibling key survives. The line after the write\n * is what a hook here would now resolve, which differs from the value written\n * when an outer layer is tighter.\n */\nasync function setRouterKey(\n key: RouterConfigKey,\n value: string,\n ctx: CommandContext,\n project: { local: boolean } | undefined,\n): Promise<CommandResult> {\n const field = key === 'router.enabled' ? 'enabled' : 'context';\n const parsed = field === 'enabled' ? parseBoolean(value) : parseRouterContext(value);\n let written: RenderedSetting;\n if (project === undefined) {\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n router: { ...existing.router, [field]: parsed },\n }));\n written = { value: parsed, source: 'file', path: configPath(ctx.dataDir) };\n } else {\n const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });\n await persistProjectRouter(path, field, parsed);\n written = { value: parsed, source: project.local ? 'local' : 'project', path };\n }\n const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n const humanLines = [formatLine(key, written)];\n if (effective.value !== written.value) {\n humanLines.push(\n `Still ${String(effective.value)} here: ${effective.path ?? 'the default'} is tighter, and a nearer file can only tighten an outer one.`,\n );\n }\n if (project?.local === true) {\n humanLines.push('Keep .tenjin/config.local.json out of git: add it to .gitignore.');\n }\n return { data: { key, ...written, effective }, humanLines };\n}\n\nfunction parseRouterContext(value: string): RouterContext {\n const found = ROUTER_CONTEXTS.find((context) => context === value);\n if (found !== undefined) return found;\n throw new CliError('USAGE', `Invalid router.context: ${JSON.stringify(value)}`, {\n fix: 'Use \"session\" or \"turn\".',\n });\n}\n\n/**\n * Merge one router key into a project file. It holds the router block and\n * nothing else this CLI reads, so it is written 0644 like any committed file;\n * an existing file that is not a JSON object is refused rather than replaced.\n * The read, merge and write run under the same cross-process lock the global\n * writer takes, so two concurrent sets both land.\n */\nasync function persistProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o755 });\n const lockPath = `${path}.lock`;\n try {\n await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));\n } catch (err) {\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nasync function mergeProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n // Through the one parser: a file that is not an object, or whose block is\n // invalid, is refused rather than replaced. A router subkey this build does\n // not know rides along untouched, as in the global file; it is never read.\n const existing = await readProjectRouterFile(path);\n const block = existing?.json.router;\n const next = {\n ...(existing?.json ?? {}),\n router: { ...(block !== undefined ? (block as object) : {}), [field]: value },\n };\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o755,\n });\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The one writer of a `hooks.<arm>` boolean, through the same locked merge-write\n * every `config set` uses, so a sibling arm or an unknown block a newer CLI\n * wrote survives. `config set hooks.<arm>` and `tenjin hooks enable|disable`\n * are two spellings of this call and never two writers.\n */\nexport async function persistHookArm(dir: string, arm: HookArm, value: boolean): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [arm]: value },\n }));\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Remember, or forget, a project directory this machine wired with\n * `install --project`. `tenjin update` spawns its refresh from the HOME\n * directory, so a project install is unfindable by looking around; this list is\n * how a later refresh reaches it. Absolute paths, de-duplicated, and pruned\n * when a project is uninstalled or its settings file stops carrying our\n * entries.\n */\nexport async function persistRouterProject(\n dir: string,\n projectDir: string,\n present = true,\n): Promise<void> {\n await persist(dir, (existing) => {\n const known = new Set(existing.install?.routerProjects ?? []);\n if (present) known.add(projectDir);\n else known.delete(projectDir);\n return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };\n });\n}\n\n/** Absent-only automatic router defaults; defined beside the spend question that shows them. */\nexport { ROUTER_DEFAULTS, type RouterLimits };\n\nexport interface RouterDefaultsResult {\n /** Keys this run wrote, because the file did not name them or the user named a new value. */\n set: string[];\n /** Keys the operator had already written, left exactly as they are. */\n kept: string[];\n removed: string[];\n}\n\n/** Remove/report retired keys in the same locked write. Refresh preserves absent\n * current settings; a fresh install fills only missing automatic limits, with the\n * values the person approved or chose. A key `limits` leaves out stays absent,\n * and the code default ($0.25 a call, $5 a day) holds for it: that is an install\n * nobody answered. A key in `chosen` is an amount the\n * user named for this install (`--max-auto-spend`, `--session-budget`), so it\n * replaces what the file holds. */\nexport async function persistRouterDefaults(\n dir: string,\n refresh = false,\n limits: Partial<RouterLimits> = ROUTER_DEFAULTS,\n chosen: readonly (keyof RouterLimits)[] = [],\n): Promise<RouterDefaultsResult> {\n const result: RouterDefaultsResult = { set: [], kept: [], removed: [] };\n if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;\n await persist(dir, (existing) => {\n const next: PartialConfig = { ...existing };\n result.removed = retiredPaymentKeys(existing);\n for (const key of result.removed) delete next[key];\n if (refresh) return next;\n for (const key of Object.keys(ROUTER_DEFAULTS) as (keyof RouterLimits)[]) {\n const value = limits[key];\n if (existing[key] !== undefined && !chosen.includes(key)) result.kept.push(key);\n else if (value !== undefined) {\n next[key] = value;\n result.set.push(key);\n }\n }\n return next;\n });\n return result;\n}\n\n/**\n * Record the settled harness selection through the same locked merge-write. It\n * replaces the previous record rather than unioning with it: the last operator\n * answer is the current intent. Doctor still re-probes detection independently;\n * the record keeps a deliberately selected but currently undetected harness in play.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly Harness[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\n/**\n * Record the EXACT free-verb rules `install` declined, through the same locked\n * read-modify-write every `config set` uses. Set to whatever was pending at the\n * moment of `--no-grant`; cleared back to `[]` the moment an install\n * actually wires the allowlist, or finds it already fully satisfied. `--refresh` subtracts this list from what it would otherwise\n * report as pending, so a settled no stays settled per rule — without also\n * silencing a genuinely NEW rule a later version adds (tenjin-agent#234).\n */\nexport async function persistGrantDeclined(dir: string, declined: string[]): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, grantDeclined: declined },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if (key === 'bazaarPay' || key === 'confirm') {\n throw new CliError('USAGE', `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });\n }\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n if (key === 'publish.ackServerWarnings') {\n return {\n value: settings.publishAckServerWarnings.value,\n source: settings.publishAckServerWarnings.source,\n };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: the arm's boolean and where it came from. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const { value, source } = settings.hooks[key.slice('hooks.'.length) as HookArm];\n return { value, source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n // REDACTED IN THE MACHINE ENVELOPE TOO, not just in the human line. `config\n // --json` is what an agent reads and what a bug report pastes, and the whole\n // point of a door key is that it opens the door for whoever holds it. What a\n // caller actually needs from this key is whether team mode is on, and\n // set/unset says exactly that. The value is still readable, by the operator,\n // in ~/.tenjin/config.json.\n if (key === 'shelfBypassSecret') {\n return { value: typeof stored === 'string' && stored.length > 0 ? 'set' : 'unset' };\n }\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'sessionBudget' && stored === 'none') return { value: null };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'sessionBudget':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'maxAutoSpend':\n return parseAutoSpend(value);\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'publicShelfUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'shelfBypassSecret':\n // A free string: it is whatever Vercel generated. Empty clears it, which\n // is how team mode is turned back off.\n return value.trim();\n case 'evalCohort':\n return parseBoolean(value);\n case 'bazaarRegistries':\n return parseRegistryList(value);\n }\n}\n\n/** A per-call limit, refused below the $0.25 floor (and on a bad amount). */\nfunction parseAutoSpend(value: string): string {\n const atomic = parseUsdToAtomic(value);\n if (BigInt(atomic) < MAX_AUTO_SPEND_FLOOR_ATOMIC) {\n throw new CliError('USAGE', `maxAutoSpend ${value} is below the 0.25 USD minimum.`, {\n fix: MAX_AUTO_SPEND_FLOOR_WHY,\n });\n }\n return atomic;\n}\n\n/** \"\" clears to []; comma-split, each entry an absolute http(s) URL. */\nfunction parseRegistryList(value: string): string[] {\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n .map((entry) => parseHttpUrl(entry));\n}\n\n// Boolean settings accept both on/off and true/false.\nfunction parseBoolean(value: string): boolean {\n if (value === 'true' || value === 'on') return true;\n if (value === 'false' || value === 'off') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\" (or \"true\"/\"false\").',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n // 0600, matching lib/config.ts's `writeConfig`: this file holds\n // `shelfBypassSecret`, and this is the writer `config set` uses to put it\n // there. See that function for why dirMode alone is not enough.\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n // A router key from a project names its file: which of several is in force is the question.\n const where =\n entry.path !== undefined && (entry.source === 'project' || entry.source === 'local')\n ? ` ${entry.path}`\n : '';\n return ` ${label} ${displayValue(entry)} ${style('dim', `(${entry.source}${where})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${style('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${style('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (value === null) return 'none (no daily limit)';\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n return value; // 'always', baseUrl, rpcUrl\n}\n","import { chmod, lstat, mkdir, readFile, realpath, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { codexRulesPath, grantedPrefixes, rulesFileBody, verifyPrefixAllowed } from './codex-rules';\nexport { removeCodexGrant } from './codex-rules';\nimport type { PublishMode } from './config';\n\n/**\n * The one place the CLI WRITES a permission grant into a harness's own settings\n * file, so the invariants live here rather than at the call site:\n *\n * - OPT-OUT, AND DISCLOSED. Every install writes the free tier, because an\n * unattended agent that gets denied is the failure this whole file exists to\n * prevent. `--no-grant` refuses it outright, and every run that\n * writes says how many rules landed and in which file. What keeps that defensible is the next two invariants: the grant is a\n * fixed free tier, and it can never widen.\n * - TWO FIXED SETS, AND NOT PARAMETERIZED. The writer takes no rule argument.\n * It takes a {@link PublishMode}, and that selects between exactly two\n * hardcoded constants: {@link FREE_VERB_RULES}, and those plus\n * {@link MODE_GATED_RULES}. So there is no call path — no flag, no config\n * key, no future caller — that can make it write `buy`, `wallet send`,\n * `config set`, `wallet create`, `mcp`, `install`, or a broad\n * `Bash(tenjin:*)`. A CLI that could widen its own permission grant is exactly\n * what this shape rules out.\n *\n * The publish rule is gated on the mode and on nothing else. INSTALLING\n * TENJIN IS THE CONSENT for it (owner call, PR #164): every install settles\n * `publish.mode` at `auto` unless told otherwise, and the FIRST install\n * writes this rule alongside the free tier rather than waiting for a second\n * run to read that default back as a choice. What keeps it defensible is\n * disclosure rather than provenance — the install output names the mode,\n * this rule, and the three ways out. Being on `auto` already means \"a clean\n * publish proceeds without asking\", and a harness prompt in front of it asks\n * that same question again somewhere the mode cannot answer (#161). Going\n * back to `review` RETRACTS the rule, on the next `install` or immediately\n * through `config set publish.mode review`, so a grant never outlives the\n * mode that justified it; `uninstall` reclaims it outright.\n *\n * What this does NOT loosen: the rule clears the HARNESS prompt and nothing\n * else. The CLI's own gates are untouched — the deterministic scan blocks a\n * hard finding in every mode and no `--yes` clears it, and `review` still\n * asks per publish. An agent cannot reach `install` or `config set` on its\n * own either; both are never-allowlisted.\n * - ADDITIVE, PLUS ONE RETRACTION THAT IS STILL OURS. Every other key in the\n * file, and every allow-rule we did not write, is copied through verbatim in\n * its original order; missing rules are appended. The single exception is\n * {@link LEGACY_ALLOWLIST_RULES}: a rule an EARLIER version of this same\n * writer put there and this one no longer recommends. Leaving it would mean\n * a user who updates and re-runs `install` keeps a grant for a command that\n * no longer exists, which is bloat we created and only we can clear. It\n * widens nothing — the set is disjoint from what we write, a test pins that\n * — and every removal is reported like every addition. A re-run on a current\n * machine still changes nothing.\n * - NEVER CLOBBERS. A settings file we cannot parse, or whose `permissions` /\n * `permissions.allow` is not the shape we expect, is left untouched and\n * reported as skipped. We do not \"repair\" someone's hand-edited config.\n *\n * The rules mirror lib/permissions.ts's ALWAYS_SAFE_ALLOWLIST (the block\n * `doctor` prints and the README quotes) and are duplicated as literals on\n * purpose: that module is a DOCUMENT whose safe tier could grow, and a widened\n * tier must not silently widen what install writes. A test pins the two lists\n * equal, so drift is a red build rather than a broader grant.\n */\n\n/** Claude Code's user-level settings file, the only file this module writes. */\nexport function claudeSettingsPath(homeDir: string): string {\n return join(homeDir, '.claude', 'settings.json');\n}\n\n/**\n * What a harness's grant state IS, in the four words `doctor` reports it with.\n * Deliberately separate from {@link PermissionsSkipReason}, which is about one\n * WRITE; this is about a machine.\n */\nexport type PermissionState = 'granted' | 'pending' | 'unsupported' | 'skipped' | 'unknown';\n\nexport interface HarnessPermissions {\n harness: string;\n state: PermissionState;\n /** The file consulted, absent when the harness has none. */\n path?: string;\n /** Rules of ours in force there. Always empty for an `absent` surface, which\n * is the point: a Codex machine has no `Bash(...)` rules to list. */\n rules: string[];\n /** Rules this machine's mode calls for and does not have. */\n missing: string[];\n /** One line an operator can act on. */\n detail: string;\n fix?: string;\n}\n\n/**\n * Apply the operator's persisted `--no-grant` decision to a native grant\n * inspection. Both install refresh and doctor use this exact projection so a\n * settled decline cannot be reported as pending by one surface and skipped by\n * the other. Exact-rule filtering deliberately lets a rule added by a later\n * version surface normally.\n */\nexport function applyGrantDecline(\n report: HarnessPermissions,\n declined: readonly string[],\n): HarnessPermissions {\n if (report.state !== 'pending' || report.missing.length === 0 || declined.length === 0) {\n return report;\n }\n const declinedSet = new Set(declined);\n const missing = report.missing.filter((rule) => !declinedSet.has(rule));\n if (missing.length === report.missing.length) return report;\n if (missing.length > 0) {\n return {\n ...report,\n missing,\n detail: `${missing.length} of this mode's rules remain missing; ${report.missing.length - missing.length} were explicitly declined`,\n };\n }\n return {\n harness: report.harness,\n state: 'skipped',\n ...(report.path !== undefined ? { path: report.path } : {}),\n rules: report.rules,\n missing,\n detail: 'the command grant was explicitly declined',\n };\n}\n\n/** Read Claude Code's settings-native grant without dispatching on a harness id. */\nexport async function inspectClaudeGrant(\n homeDir: string,\n mode: PublishMode,\n): Promise<HarnessPermissions> {\n const found = await inspectAllowlist(homeDir, mode);\n if ('result' in found) {\n const refused = found.result;\n return {\n harness: 'claude',\n state: 'unknown',\n ...(refused.path !== undefined ? { path: refused.path } : {}),\n rules: [],\n missing: [],\n detail: refused.warning ?? `${claudeSettingsPath(homeDir)} could not be read.`,\n ...(refused.fix !== undefined ? { fix: refused.fix } : {}),\n };\n }\n const missing = [...found.added];\n return {\n harness: 'claude',\n state: missing.length === 0 ? 'granted' : 'pending',\n path: found.path,\n rules: [...found.alreadyPresent],\n missing,\n detail:\n missing.length === 0\n ? `${found.alreadyPresent.length} rules in ${found.path}`\n : `${missing.length} of this mode's rules are missing from ${found.path}`,\n ...(missing.length === 0 ? {} : { fix: 'tenjin install' }),\n };\n}\n\n/**\n * Codex's grant, read back and then PUT TO CODEX.\n *\n * Two questions, and the second settles it: does the file say what this mode\n * calls for, and does the binary agree it grants that. A `.rules` file that\n * fails to parse is silent until a session runs, so a reader that stopped at\n * \"the file matches\" would report `granted` over a file Codex is discarding.\n * With no `codex` to ask, the file's answer stands and the detail says so.\n */\n/** Bring an already-correct grant file back to 0600 if something widened it. */\nasync function tighten(path: string): Promise<void> {\n if (process.platform === 'win32') return;\n const found = await stat(path).catch(() => null);\n if (found === null || (found.mode & 0o077) === 0) return;\n await chmod(path, 0o600).catch(() => undefined);\n}\n\nexport async function inspectCodexGrant(\n homeDir: string,\n mode: PublishMode,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<HarnessPermissions> {\n const path = codexRulesPath(homeDir, env);\n const writable = rulesForPublishMode(mode);\n const want = rulesFileBody(writable);\n const rules = grantedPrefixes(writable).map((tokens) => tokens.join(' '));\n const found = await readFile(path, 'utf8').catch(() => null);\n if (found !== want) {\n return {\n harness: 'codex',\n state: 'pending',\n path,\n rules: [],\n missing: rules,\n detail:\n found === null\n ? `no grant is installed at ${path}`\n : `${path} does not match what publish.mode ${mode} calls for`,\n fix: 'tenjin install',\n };\n }\n // One representative prefix, not all eleven: they come from one generated\n // body, so they parse or fail together, and a self-test that spawns eleven\n // processes on every `doctor` is a cost with no extra answer in it. The one\n // asked about is the consequential one — the mode-gated `publish` where the\n // mode carries it.\n const probe = grantedPrefixes(writable).at(-1);\n const agreed = probe === undefined ? null : await verifyPrefixAllowed(path, probe, env);\n if (agreed === false) {\n return {\n harness: 'codex',\n state: 'pending',\n path,\n rules: [],\n missing: rules,\n detail: `${path} is installed but Codex does not read it as granting \\`${probe?.join(' ')}\\``,\n fix: 'tenjin install',\n };\n }\n // GRANTED ONLY WHEN CODEX SAYS SO. A file that matches what the mode calls\n // for is not the same fact as a grant in force: on a Codex too old for the\n // rules layer, or with no `codex` on PATH at all, this file is inert and\n // reporting `granted` over it would be the same overclaim as the Claude\n // rules on a Codex machine (tenjin-agent#342). `unknown` says the write\n // landed and the question could not be put.\n if (agreed === null) {\n return {\n harness: 'codex',\n state: 'unknown',\n path,\n rules,\n missing: [],\n detail: `${rules.length} prefixes written to ${path}, but codex could not be asked whether it reads them as a grant`,\n fix: 'Check `codex execpolicy check --rules <file> tenjin publish x` on the machine itself.',\n };\n }\n return {\n harness: 'codex',\n state: 'granted',\n path,\n rules,\n missing: [],\n detail: `${rules.length} prefixes in ${path}, confirmed by codex execpolicy`,\n };\n}\n\n/** What one Codex grant write did. */\nexport interface CodexGrantResult {\n path: string;\n /** The prefixes now granted there, as space-joined command prefixes. */\n granted: string[];\n /** True when this run changed the file. */\n wrote: boolean;\n /** Present when nothing could be written; the file was left as found. */\n error?: string;\n}\n\n/**\n * Write Codex's grant for `mode`, whole.\n *\n * TAKES A MODE, NOT RULES, exactly as {@link wireFreeVerbAllowlist} does: the\n * two fixed constants are all either writer can produce, so no caller and no\n * future flag can widen one. lib/codex-rules.ts only spells the result.\n *\n * Idempotent by construction, the body being a pure function of the mode. And\n * `review` regenerates it WITHOUT the mode-gated pair, which IS the retraction\n * — no separate remove path to forget, because narrowing and widening are one\n * operation.\n */\nexport async function wireCodexGrant(\n homeDir: string,\n mode: PublishMode,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<CodexGrantResult> {\n const path = codexRulesPath(homeDir, env);\n const rules = rulesForPublishMode(mode);\n const body = rulesFileBody(rules);\n const granted = grantedPrefixes(rules).map((t) => t.join(' '));\n try {\n await mkdir(dirname(path), { recursive: true });\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current === body) {\n // Byte-identical is not the same as correct. This file is a standing\n // decision about which commands run unattended, so a dotfiles sync or a\n // stray chmod that widened it must be converged even on the run that\n // writes nothing -- otherwise re-installing leaves a group-writable\n // grant exactly as it found it. Mirrors `tightenFile` in\n // lib/harness-hooks.ts, for the same reason.\n await tighten(path);\n return { path, granted, wrote: false };\n }\n // 0600 for the same reason the hooks file gets it: this is a standing\n // decision about which commands run without asking, and a file another\n // account can append to is a file that can widen it.\n await writeFileAtomic(path, body, { mode: 0o600 });\n return { path, granted, wrote: true };\n } catch (err) {\n return {\n path,\n granted: [],\n wrote: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/**\n * The exact rules install may add. Free verbs only: none of them can spend\n * USDC, though `read` and `doctor` do open the keystore. See lib/permissions.ts\n * for the per-verb notes and for the flag caveat that qualifies every prefix\n * rule.\n */\nexport const FREE_VERB_RULES: readonly string[] = [\n 'Bash(tenjin search:*)',\n 'Bash(tenjin wallet fund:*)',\n 'Bash(tenjin inspect:*)',\n 'Bash(tenjin read:*)',\n 'Bash(tenjin outcome:*)',\n 'Bash(tenjin doctor:*)',\n 'Bash(tenjin wallet show:*)',\n 'Bash(tenjin wallet balance:*)',\n 'Bash(tenjin config get:*)',\n];\n\n/**\n * The rule `publish.mode` gates, mirroring lib/permissions.ts's\n * PUBLISH_MODE_ALLOWLIST and duplicated as a literal for the same reason\n * {@link FREE_VERB_RULES} is: that module is a DOCUMENT, and an edit there must\n * not silently change what this file writes. A test pins the two together.\n *\n * Deliberately NOT a member of {@link FREE_VERB_RULES}: it can neither spend nor\n * move keys, but it publishes publicly under the operator's identity, so it is\n * not free-tier and never rides along with it.\n */\nexport const PUBLISH_MODE_RULE = 'Bash(tenjin publish:*)';\n\n/**\n * The other half of the mode-gated pair. `edit` runs the SAME publish.mode\n * consent gate in the CLI (lib/consent.ts's needsConfirmation), touches only\n * posts this wallet already owns, spends nothing, and creates no new public\n * content — strictly narrower than the publish rule it travels with. A mode that\n * can publish a new post unattended but cannot fix that post's price is the\n * asymmetry the mode exists to remove.\n */\nexport const EDIT_MODE_RULE = 'Bash(tenjin edit:*)';\n\n/** The pair the publish modes carry, in the order they are written and reported. */\nexport const MODE_GATED_RULES: readonly string[] = [PUBLISH_MODE_RULE, EDIT_MODE_RULE];\n\n/**\n * Verb fragments that must never appear in {@link MODE_GATED_RULES}: the rail\n * {@link FORBIDDEN_VERB_FRAGMENTS} gives the free tier, minus the two verbs this\n * set exists to carry.\n *\n * It needs that rail more than the free tier does. This set was mode-conditional\n * prose before and is WRITTEN BY DEFAULT on every install now, so a line added\n * here ships a grant to every machine — and without this, adding\n * `Bash(tenjin buy:*)` to the pair passes the entire suite, because every other\n * assertion on it compares against PUBLISH_MODE_ALLOWLIST, a document editable in\n * the same commit.\n */\nexport const MODE_GATED_FORBIDDEN_FRAGMENTS: readonly string[] = [\n 'tenjin buy',\n 'tenjin wallet send',\n // The mode carries publish and edit and stops there. `delete` destroys what\n // those two put up, and consent to publish is not consent to destroy.\n 'tenjin delete',\n 'tenjin config set',\n 'tenjin wallet create',\n 'tenjin mcp',\n 'tenjin install',\n 'tenjin update',\n];\n\n/**\n * Exactly what may be written for `mode`. The two return values are the only two\n * rule sets this module can produce.\n */\nexport function rulesForPublishMode(mode: PublishMode): readonly string[] {\n return mode === 'review' ? FREE_VERB_RULES : [...FREE_VERB_RULES, ...MODE_GATED_RULES];\n}\n\n/**\n * What this run should sweep out: what an older version wrote, plus the publish\n * rule when the mode no longer justifies it. A retraction is always a rule this\n * CLI wrote under a setting the operator has since changed, and it is reported\n * exactly like an addition.\n */\nfunction retiredFor(mode: PublishMode): Set<string> {\n const retired = new Set<string>(LEGACY_ALLOWLIST_RULES);\n if (mode === 'review') for (const rule of MODE_GATED_RULES) retired.add(rule);\n return retired;\n}\n\n/**\n * Rules a PRIOR version of this writer put in `permissions.allow` and this one\n * no longer writes — FREE TIER OR MODE-GATED, which is why this is not\n * `LEGACY_FREE_VERB_RULES` any more. Nothing is stranded today, but the day a\n * mode-gated rule is renamed or dropped, every machine holding it would keep a\n * publish-capable allow-line that no `install` and no `uninstall` reclaims. That\n * is one layer above the bug this list was created to fix, so the list covers\n * both layers. BOTH paths read it: `install` removes them on its next\n * run, `uninstall` reclaims them as its own. NEITHER path ever writes one — the\n * writable set is {@link FREE_VERB_RULES} and this list is disjoint from it, so\n * a retired rule can only ever be deleted, never re-added. A test pins that\n * disjointness, because the day the two overlap is the day install starts\n * re-adding a grant for a command that does not exist.\n *\n * Why it has to exist at all: a rule dropped from FREE_VERB_RULES is otherwise\n * invisible to every later version. The operator keeps an allow-line for a\n * command that no longer exists, `install` walks past it because it is not in\n * the set it writes, and `uninstall` walks past it because it is no longer\n * \"ours\". It IS ours — we wrote it — and a user who updates and re-runs\n * `install` should end up with exactly the current tier and nothing we left\n * behind. Anything retired from the free tier belongs here.\n *\n * `Bash(tenjin candidate list:*)` is the first entry: the candidate pen was\n * removed, and machines installed before that still carry its rule.\n */\nexport const LEGACY_ALLOWLIST_RULES: readonly string[] = [\n 'Bash(tenjin candidate list:*)',\n 'Bash(tenjin fund:*)',\n];\n\n/**\n * Verb fragments that must never appear in {@link FREE_VERB_RULES}. Asserted by\n * a test rather than at runtime: the constant above is not reachable from any\n * input, so the only way one of these lands in it is an edit to this file, and a\n * test is what catches an edit.\n */\nexport const FORBIDDEN_VERB_FRAGMENTS: readonly string[] = [\n 'tenjin buy',\n 'tenjin publish',\n 'tenjin edit',\n 'tenjin delete',\n 'tenjin wallet send',\n 'tenjin config set',\n 'tenjin wallet create',\n 'tenjin mcp',\n 'tenjin install',\n 'Bash(tenjin:*)',\n];\n\n/**\n * Why no rules were written. Every value is a reason to leave the file alone,\n * never a partial write: the writer either appends all missing rules or none.\n */\nexport type PermissionsSkipReason =\n /**\n * The harness has no supported surface for a persistent, command-scoped\n * grant, so there is nothing to write and no operator step that would make\n * one appear. NOT `harness-not-claude`, which is what this was called: that\n * name describes our implementation rather than the harness, and it let\n * every reader downstream assume a Claude-shaped grant was in force anyway\n * (tenjin-agent#342). The adapter registrar owns that capability now.\n */\n | 'harness-unsupported'\n | 'not-requested'\n | 'declined'\n | 'dry-run'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\n/**\n * The mode-gated half of a write, as DATA rather than as prose a caller\n * re-derives.\n *\n * Every surface that reports the grant reads this one object: the walkthrough's\n * disclosure line, the `--json` envelope on the headless path (where nobody was\n * asked and the output is the only disclosure there is), and the tests. The\n * earlier shape returned one undifferentiated `added`, so each surface split the\n * tiers itself — and two of them counted `publish` and `edit` as free verbs while\n * a third never rendered at all.\n */\nexport interface ModeGrant {\n /** The mode-gated rules now in effect on this machine. */\n rules: string[];\n /**\n * Written by THIS run, already there, or one of each. On a `--dry-run` plan it\n * is what a real run WOULD produce, and {@link PermissionsResult.planned} is the\n * field that says so; the `disclosure` sentence changes tense to match.\n */\n state: 'added' | 'already-present' | 'mixed';\n /** The plain sentence naming what the grant allows; the walkthrough colorizes it. */\n disclosure: string;\n /** Every command that takes it back, in the order the walkthrough prints them. */\n undo: string[];\n}\n\n/** The three undos, named wherever a mode-gated grant is reported. */\nexport const MODE_GRANT_UNDO: readonly string[] = [\n 'tenjin install --publish-mode review',\n 'tenjin config set publish.mode review',\n 'tenjin uninstall',\n];\n\n/**\n * Build the grant record for `mode`, or undefined when the mode carries no rules\n * or none of them ended up on this machine.\n */\nfunction modeGrantFor(\n mode: PublishMode,\n added: readonly string[],\n present: readonly string[],\n planned: boolean,\n): ModeGrant | undefined {\n const wasAdded = MODE_GATED_RULES.filter((r) => added.includes(r));\n const wasPresent = MODE_GATED_RULES.filter((r) => present.includes(r));\n const rules = [...wasAdded, ...wasPresent];\n if (rules.length === 0) return undefined;\n const state =\n wasAdded.length === 0 ? 'already-present' : wasPresent.length === 0 ? 'added' : 'mixed';\n // A plan says \"would be added\". The `planned` flag alone left this sentence in\n // the past tense, and it is the one string a reader quotes back.\n const verb =\n state === 'already-present'\n ? 'already present'\n : state === 'mixed'\n ? planned\n ? 'would be in place'\n : 'in place'\n : planned\n ? 'would be added'\n : 'added';\n return {\n rules: MODE_GATED_RULES.filter((r) => rules.includes(r)),\n state,\n disclosure: `${MODE_GATED_RULES.join(' and ')} ${verb}: on publish.mode ${mode} your agent can publish to the public marketplace under your identity, update its own posts, and open your wallet keystore to sign, without a harness prompt.`,\n undo: [...MODE_GRANT_UNDO],\n };\n}\n\nexport interface PermissionsResult {\n /** The harness this outcome is about; only `claude` has a settings file we write. */\n harness: string;\n /**\n * The settings file, reported even when nothing was written so a human can go\n * look. ABSENT when the harness has no such file: naming a Claude path on a\n * Codex-only install would point the envelope's reader at a file that has\n * nothing to do with their harness.\n *\n * ONE EXCEPTION, in `install`'s `withRetraction`: a `review` run retracts from\n * `~/.claude/settings.json` above the harness guard, so a non-Claude result\n * carrying a non-empty `removed` carries that path too. The reason the general\n * rule exists is inverted there, because the run did change that file and the\n * operator cannot check which one without its name.\n */\n path?: string;\n added: string[];\n alreadyPresent: string[];\n /**\n * The FREE-TIER halves of the two lists above. Every count line reads these:\n * `publish` and `edit` are not free verbs, and a line calling eleven rules\n * \"free tenjin commands\" contradicts both this module and the `doctor` pointer\n * printed on the next screen.\n */\n /**\n * True when this result is a PLAN rather than a record: `--dry-run` fills\n * `added`, `alreadyPresent` and `modeGrant` with what a real run would do and\n * writes nothing. Every reader that treats a non-empty `added` as \"this landed\"\n * has to check it, which is the point of a flag rather than a parallel shape.\n */\n planned?: boolean;\n addedFree: string[];\n alreadyPresentFree: string[];\n /** The mode-gated half, or absent when this write carried none. */\n modeGrant?: ModeGrant;\n /**\n * Rules an EARLIER version of this writer wrote and this one retired, removed\n * on this run. Almost always empty; non-empty exactly once, on the first\n * install after an update that retired something.\n */\n removed: string[];\n skipped?: PermissionsSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n /**\n * The exact command that changes this outcome, present on EVERY skipped state.\n * Same contract as a CliError's `fix`: a machine consumer reading the envelope\n * gets the remedy as a field, never as prose it has to interpret. The human\n * walkthrough renders its own wording from `skipped`, so the two never collide.\n */\n fix?: string;\n}\n\n/**\n * The command that turns a skip into a write. Kept beside the reason vocabulary\n * so a new reason cannot ship without one.\n *\n * `harness-unsupported` is the exception that proves it: no command turns it\n * into a write, so its `fix` says what the harness itself does instead. Naming\n * `tenjin doctor` there, as this used to, sent an operator to a page of Claude\n * rules and let them read those as their own (tenjin-agent#342).\n */\nfunction fixFor(reason: PermissionsSkipReason, harness = 'claude'): string {\n switch (reason) {\n case 'harness-unsupported':\n return `No permission rules were written: ${harness} has no surface for them.`;\n case 'not-requested':\n case 'declined':\n case 'dry-run':\n return 'Add them with `tenjin install`.';\n case 'changed-since-read':\n return 'Another process changed the file mid-run; re-run `tenjin install`.';\n default:\n return 'Fix the reported file, then run `tenjin install`.';\n }\n}\n\n/**\n * The tier split plus the grant record, derived once from the two rule lists so\n * no caller re-derives it. Spread into every non-skipped result.\n */\nfunction tiers(\n added: readonly string[],\n alreadyPresent: readonly string[],\n mode: PublishMode,\n planned = false,\n): Pick<PermissionsResult, 'addedFree' | 'alreadyPresentFree'> & { modeGrant?: ModeGrant } {\n const gated = new Set<string>(MODE_GATED_RULES);\n const grant = modeGrantFor(mode, added, alreadyPresent, planned);\n return {\n addedFree: added.filter((r) => !gated.has(r)),\n alreadyPresentFree: alreadyPresent.filter((r) => !gated.has(r)),\n ...(grant !== undefined ? { modeGrant: grant } : {}),\n };\n}\n\nfunction skip(\n harness: string,\n path: string | undefined,\n reason: PermissionsSkipReason,\n warning?: string,\n): PermissionsResult {\n return {\n harness,\n ...(path !== undefined ? { path } : {}),\n added: [],\n removed: [],\n alreadyPresent: [],\n addedFree: [],\n alreadyPresentFree: [],\n skipped: reason,\n ...(warning !== undefined ? { warning } : {}),\n fix: fixFor(reason, harness),\n };\n}\n\n/** A decision NOT to write, shaped like a write outcome so the caller has one type. */\nexport function permissionsSkipped(\n harness: string,\n homeDir: string,\n reason: PermissionsSkipReason,\n): PermissionsResult {\n // A PermissionsResult is THIS writer's receipt, so its `path` is this\n // writer's file or nothing. Naming ~/.claude/settings.json to a Codex\n // operator points them at a file that is nothing to do with their harness;\n // naming Codex's rules file here would be worse, because the sentence around\n // it is about rules that never went there (tenjin-agent#342).\n const path = harness === 'claude' ? claudeSettingsPath(homeDir) : undefined;\n return skip(harness, path, reason);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Write settings.json KEEPING THE MODE IT HAS. Operators `chmod 600` this file —\n * it commonly holds an `env` block and `apiKeyHelper` — and handing it back\n * world-readable because we appended a permission line is a downgrade nobody\n * asked for. A file we are creating gets the platform default. Mirrors\n * lib/skill-writer.ts, which already does this for skills.\n */\nasync function writeSettings(path: string, next: Record<string, unknown>): Promise<void> {\n const current = await stat(path).catch(() => null);\n await writeFileAtomic(\n path,\n `${JSON.stringify(next, null, 2)}\\n`,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n}\n\n/**\n * Remove {@link MODE_GATED_RULES}, and nothing else, from `permissions.allow`.\n *\n * SEPARATE FROM THE ADDITIVE WRITER, and that separation is the point. Retraction\n * used to ride the same call that appends the free tier, so it inherited that\n * call's precondition and bailed out whenever the free tier was not byte-exact —\n * silently, in the tightening direction, on two of the three commands the consent\n * decision names as its own undo. The stated rationale (a publish rule without\n * the free tier beside it was not written by our install) does not survive the\n * ordinary case: the first release that adds a tenth free verb makes every\n * existing machine's tier incomplete while the pair is genuinely ours, and an\n * unparsable file is UNKNOWN rather than not-ours.\n *\n * So `review` always retracts. This adds nothing, ever: it can only shorten the\n * allow list, which is why it needs no consent and no complete-tier precondition.\n */\nexport async function retractModeGatedRules(homeDir: string): Promise<PermissionsResult> {\n const found = await inspectAllowlist(homeDir, 'review');\n if ('result' in found) {\n // Unknown, not absent. The one case that cannot proceed says so, names the\n // rules and the file, and hands over the command that always works.\n const refused = found.result;\n return {\n ...refused,\n fix: `${refused.path ?? claudeSettingsPath(homeDir)} could not be read, so ${MODE_GATED_RULES.join(' and ')} may still be allowed there. Remove those lines by hand, or run \\`tenjin uninstall\\`.`,\n };\n }\n const { path, raw, settings, permissions, allow } = found;\n const gated = new Set<string>(MODE_GATED_RULES);\n const removed = allow.filter((r): r is string => typeof r === 'string' && gated.has(r));\n if (removed.length === 0) {\n return {\n harness: 'claude',\n path,\n added: [],\n alreadyPresent: [],\n addedFree: [],\n alreadyPresentFree: [],\n removed: [],\n };\n }\n const kept = allow.filter((r) => !(typeof r === 'string' && gated.has(r)));\n const next = { ...settings, permissions: { ...permissions, allow: kept } };\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current !== raw) {\n return skip(\n 'claude',\n path,\n 'changed-since-read',\n `${path} changed while it was being updated, so nothing was written. Re-run to retract ${MODE_GATED_RULES.join(' and ')}.`,\n );\n }\n await writeSettings(path, next);\n return {\n harness: 'claude',\n path,\n added: [],\n alreadyPresent: [],\n addedFree: [],\n alreadyPresentFree: [],\n removed,\n };\n}\n\n/**\n * Add the rules `mode` calls for to `permissions.allow` in\n * ~/.claude/settings.json. Creates the file (and the `permissions.allow` path)\n * when absent, appends only the rules that are missing, and rewrites nothing\n * else. Idempotent: a second run at the same mode returns `added: []` with every\n * rule under `alreadyPresent` and does not touch the file at all.\n */\n/**\n * What {@link wireFreeVerbAllowlist} WOULD do, without doing it.\n *\n * `--dry-run` used to report the allowlist as a bare `dry-run` skip with an empty\n * `added` and no `modeGrant`, so an operator dry-running precisely to learn\n * whether `publish` and `edit` would be granted learned nothing. It reads through\n * the same `inspectAllowlist` the writer does and fills the same fields, marked\n * `planned` so nothing mistakes a plan for a record.\n */\nexport async function planFreeVerbAllowlist(\n homeDir: string,\n mode: PublishMode = 'review',\n): Promise<PermissionsResult> {\n const found = await inspectAllowlist(homeDir, mode);\n // Unreadable, unparsable, wrong shape: a real run could not write either, and\n // the reason it gives is the honest plan.\n if ('result' in found) return { ...found.result, planned: true };\n const retired = retiredFor(mode);\n const wouldRemove = found.allow.filter(\n (r): r is string => typeof r === 'string' && retired.has(r),\n );\n return {\n harness: 'claude',\n path: found.path,\n planned: true,\n skipped: 'dry-run',\n fix: fixFor('dry-run'),\n added: [...found.added],\n alreadyPresent: [...found.alreadyPresent],\n ...tiers(found.added, found.alreadyPresent, mode, true),\n removed: wouldRemove,\n };\n}\n\nexport async function wireFreeVerbAllowlist(\n homeDir: string,\n mode: PublishMode = 'review',\n): Promise<PermissionsResult> {\n const found = await inspectAllowlist(homeDir, mode);\n if ('result' in found) return found.result;\n const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;\n // Rules an earlier version of this writer left behind, and the publish rule\n // when the mode no longer carries it. Swept on the same pass that appends, so\n // one `tenjin install` leaves a settings.json holding exactly what this\n // machine's current mode calls for and no residue from what it used to be.\n const retired = retiredFor(mode);\n const removed = allow.filter((r): r is string => typeof r === 'string' && retired.has(r));\n if (added.length === 0 && removed.length === 0) {\n return {\n harness: 'claude',\n path,\n added: [],\n alreadyPresent,\n ...tiers([], alreadyPresent, mode),\n removed: [],\n };\n }\n\n // Object spreads keep the original key order and land the rebuilt `permissions`\n // in the slot it already occupied, so a diff of the file is the appended rules,\n // the retired ones dropped, and nothing else.\n const kept = allow.filter((r) => !(typeof r === 'string' && retired.has(r)));\n const next = {\n ...settings,\n permissions: { ...permissions, allow: [...kept, ...added] },\n };\n // This is a whole-file read-modify-write, so a change landing between the read\n // and the rename would be erased in full, including keys that have nothing to do\n // with permissions. Claude Code writes this file too, so the other writer is not\n // hypothetical. Compare the bytes we based the edit on and refuse rather than\n // clobber; the operator re-runs and the merge is recomputed against what is\n // actually there.\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current !== raw) {\n return skip(\n 'claude',\n path,\n 'changed-since-read',\n `${path} changed while it was being updated, so nothing was written. Re-run \\`tenjin install\\`.`,\n );\n }\n await writeSettings(path, next);\n return {\n harness: 'claude',\n path,\n added,\n alreadyPresent,\n ...tiers(added, alreadyPresent, mode),\n removed,\n };\n}\n\n/**\n * The probe the install walkthrough uses: what is still missing, plus the outcome\n * to report when nothing is. Returning the SNAPSHOT's own result matters. Calling\n * the writer again after a zero-pending probe re-reads the file, so a rule revoked\n * between the two reads was silently re-added with no prompt, which is the one\n * thing a consent gate must not do.\n *\n * `pending` is null when the file cannot be understood; that is \"unknown\", never\n * \"already allowed\", and the caller must still ask.\n *\n * `satisfied` is returned ONLY when there is nothing to add AND nothing retired\n * to sweep. A machine that already carries every current rule plus one an older\n * version wrote is NOT satisfied: reporting it as such would short-circuit the\n * writer and strand exactly the rule the sweep exists to clear. `pending` stays\n * empty there, so the caller can tell \"nothing to grant, but work to do\" from\n * \"something to grant\" and skip the consent prompt for a run that only removes.\n */\nexport async function inspectFreeVerbRules(\n homeDir: string,\n mode: PublishMode = 'review',\n): Promise<{ pending: string[] | null; satisfied?: PermissionsResult }> {\n const found = await inspectAllowlist(homeDir, mode);\n if ('result' in found) return { pending: null };\n if (found.added.length > 0) return { pending: found.added };\n const retired = retiredFor(mode);\n if (found.allow.some((r) => typeof r === 'string' && retired.has(r))) return { pending: [] };\n return {\n pending: [],\n satisfied: {\n harness: 'claude',\n path: found.path,\n added: [],\n alreadyPresent: found.alreadyPresent,\n ...tiers([], found.alreadyPresent, mode),\n removed: [],\n },\n };\n}\n\nexport type PermissionList = 'allow' | 'deny';\n\nexport interface AllowlistInspection {\n path: string;\n /** The exact bytes read, so the commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n permissions: Record<string, unknown>;\n /** The entries of the list read: `permissions.allow`, or `permissions.deny` when asked. */\n allow: unknown[];\n added: string[];\n alreadyPresent: string[];\n}\n\n/**\n * Resolve and read the settings file, and work out which rules are missing.\n * Every refusal this module can reach is decided here, so the probe and the\n * write agree by construction about what is untouchable.\n */\nasync function inspectAllowlist(\n homeDir: string,\n mode: PublishMode,\n): Promise<AllowlistInspection | { result: PermissionsResult }> {\n return inspectAllowlistAt(claudeSettingsPath(homeDir), rulesForPublishMode(mode));\n}\n\n/**\n * The same read, for any settings file and any rule list. Every refusal this\n * module can reach is decided here, so a second writer cannot accidentally\n * skip the symlink resolution, the shape checks or the bytes a commit has to\n * compare against. `tenjin install`'s router rules go through it, its deny\n * rule included.\n */\nexport async function inspectAllowlistAt(\n declaredPath: string,\n rules: readonly string[],\n list: PermissionList = 'allow',\n): Promise<AllowlistInspection | { result: PermissionsResult }> {\n const refuse = (\n p: string,\n reason: PermissionsSkipReason,\n warning: string,\n ): { result: PermissionsResult } => ({ result: skip('claude', p, reason, warning) });\n\n // `lstat`, not `existsSync`: existsSync FOLLOWS a symlink, so a link pointing at\n // a file that is not there reads as \"absent\" and the create path below would\n // rename a regular file over the link. We need to know whether an ENTRY is\n // there, whatever it points at.\n const entry = await lstat(declaredPath).catch(() => null);\n\n // Resolve symlinks BEFORE writing. `writeFileAtomic` commits with a rename,\n // which replaces a symlink with a regular file: a settings.json linked into a\n // dotfiles repo would be severed, its target left stale, and future edits there\n // would stop reaching Claude Code. Renaming over the RESOLVED path edits the\n // file the operator actually maintains and leaves the link intact, which is\n // what this module's additive-only, never-clobber invariants promise. A link we\n // cannot resolve is left alone rather than overwritten; for a genuinely absent\n // file there is nothing to follow and we create it at the declared path.\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return refuse(\n declaredPath,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return refuse(\n path,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); no permissions were written.`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return refuse(\n path,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n if (!isPlainObject(parsed)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} is not a JSON object; it was left exactly as it is.`,\n );\n }\n settings = parsed;\n }\n\n // `permissions` and `permissions.allow` may be absent (we create them), but a\n // present one of the wrong type is someone else's structure: refuse rather\n // than replace it. Unknown entry types inside `allow` are fine and ride\n // through verbatim; they simply never match a rule.\n const permissionsValue = settings.permissions;\n if (permissionsValue !== undefined && !isPlainObject(permissionsValue)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} has a \"permissions\" key that is not an object; it was left exactly as it is.`,\n );\n }\n const permissions: Record<string, unknown> = permissionsValue ?? {};\n const allowValue = permissions[list];\n if (allowValue !== undefined && !Array.isArray(allowValue)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} has a \"permissions.${list}\" key that is not an array; it was left exactly as it is.`,\n );\n }\n const allow: unknown[] = allowValue ?? [];\n\n const present = new Set(allow.filter((e): e is string => typeof e === 'string'));\n const added = rules.filter((rule) => !present.has(rule));\n const alreadyPresent = rules.filter((rule) => present.has(rule));\n return { path, raw, settings, permissions, allow, added, alreadyPresent: [...alreadyPresent] };\n}\n\nexport interface AppendAllowlistResult {\n path: string;\n added: string[];\n alreadyPresent: string[];\n skipped?: PermissionsSkipReason;\n warning?: string;\n}\n\n/**\n * Append rules to `permissions.allow` (or `permissions.deny`) in one settings\n * file, keeping every other key. Shares {@link inspectAllowlistAt}'s refusals and the changed-since-read\n * compare, so a file this module will not touch is a file no writer here\n * touches: a symlink is resolved before the rename, an unparseable file is left\n * exactly as it is, and a write that landed underneath is refused rather than\n * erased.\n */\nexport async function appendAllowlistRules(\n declaredPath: string,\n rules: readonly string[],\n list: PermissionList = 'allow',\n): Promise<AppendAllowlistResult> {\n const found = await inspectAllowlistAt(declaredPath, rules, list);\n if ('result' in found) {\n const result = found.result;\n return {\n path: result.path ?? declaredPath,\n added: [],\n alreadyPresent: [],\n ...(result.skipped !== undefined ? { skipped: result.skipped } : {}),\n ...(result.warning !== undefined ? { warning: result.warning } : {}),\n };\n }\n const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;\n if (added.length === 0) return { path, added: [], alreadyPresent };\n const next = { ...settings, permissions: { ...permissions, [list]: [...allow, ...added] } };\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current !== raw) {\n return {\n path,\n added: [],\n alreadyPresent,\n skipped: 'changed-since-read',\n warning: `${path} changed while it was being updated, so nothing was written. Re-run \\`tenjin install\\`.`,\n };\n }\n await writeSettings(path, next);\n return { path, added, alreadyPresent };\n}\n","import { execFile } from 'node:child_process';\nimport { rm, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { codexHome } from './codex-home';\n\n/**\n * Codex's persistent command grant: `$CODEX_HOME/rules/tenjin.rules`.\n *\n * This is the same layer Codex's own approval flow writes when a person\n * chooses \"don't ask again for commands that start with ...\", and the same one\n * OpenAI's docs name for it (\"Codex writes to the user layer at\n * `~/.codex/rules/default.rules` so future runs can skip the prompt\"). Every\n * `*.rules` file in that directory is loaded, which is what makes a file of\n * our own possible.\n *\n * A FILE OF OUR OWN, NEVER `default.rules`. That one is the operator's and\n * Codex appends to it; editing it would mean rewriting a Starlark file someone\n * else owns to find our lines again. `tenjin.rules` is ours whole, the same\n * ownership boundary `lib/harness-hooks.ts` draws inside hooks.json.\n *\n * A TRANSLATOR, NOT A SECOND POLICY. Callers hand it the rule list\n * `rulesForPublishMode` already settled, so it cannot widen a grant, and it\n * does not import the tiers so the dependency runs one way. A rule it cannot\n * parse is DROPPED rather than guessed at, which makes `Bash(tenjin:*)` — the\n * blanket form — unparseable here by construction (tenjin-agent#342).\n */\n\n/** Our file in Codex's user rules layer. */\nexport function codexRulesPath(home: string, env: NodeJS.ProcessEnv = process.env): string {\n return join(codexHome(home, env), 'rules', 'tenjin.rules');\n}\n\n/**\n * `Bash(tenjin search:*)` to `[\"tenjin\", \"search\"]`, or null for anything that\n * is not exactly that shape.\n *\n * STRICT ON PURPOSE. The pattern requires at least one verb word after\n * `tenjin`, so `Bash(tenjin:*)` — the blanket rule\n * {@link FORBIDDEN_VERB_FRAGMENTS} exists to keep out — cannot be translated\n * at all rather than being translated into `[\"tenjin\"]`, which in Codex's\n * grammar would clear every subcommand there is.\n */\nexport function prefixTokens(rule: string): string[] | null {\n const m = /^Bash\\(tenjin ((?:[a-z][a-z-]* )*[a-z][a-z-]*):\\*\\)$/.exec(rule);\n const verbs = m?.[1];\n if (verbs === undefined) return null;\n return ['tenjin', ...verbs.split(' ')];\n}\n\n/** One `prefix_rule` line. Tokens are JSON-quoted, as Codex writes them. */\nexport function prefixRuleLine(tokens: readonly string[]): string {\n const pattern = tokens.map((t) => JSON.stringify(t)).join(', ');\n return `prefix_rule(pattern=[${pattern}], decision=\"allow\")`;\n}\n\n/** The token lists `rules` grants, in the order they are written. */\nexport function grantedPrefixes(rules: readonly string[]): string[][] {\n return rules.map(prefixTokens).filter((t): t is string[] => t !== null);\n}\n\n/** The file body for `rules`, byte-identical run to run so a re-install is a no-op. */\nexport function rulesFileBody(rules: readonly string[]): string {\n const lines = [\n '# Written by `tenjin install`. Change it with `tenjin config set publish.mode`',\n '# or `tenjin uninstall`, not by hand: the next install rewrites it whole.',\n '# Your own rules live in default.rules and are never touched by Tenjin.',\n '',\n ...grantedPrefixes(rules).map(prefixRuleLine),\n ];\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * Ask Codex whether it agrees a prefix is granted, using its own\n * `execpolicy check` against the file we wrote.\n *\n * THE ONLY PROOF WORTH REPORTING. Writing a file is not a grant, and a\n * Starlark file that fails to parse is silent until a session starts — `codex\n * doctor` will not tell you, and nor would we (tenjin-agent#342).\n *\n * ASK ABOUT THE INNER COMMAND, not the shell line: the session path decomposes\n * `/bin/zsh -lc '<script>'` before matching, and `execpolicy check` is a\n * raw-argv checker that does not, so the wrapped form answers nothing.\n *\n * Null means the question could not be put, and is never read as a No.\n */\nexport async function verifyPrefixAllowed(\n rulesPath: string,\n tokens: readonly string[],\n env: NodeJS.ProcessEnv = process.env,\n timeoutMs = VERIFY_MS,\n): Promise<boolean | null> {\n return await new Promise<boolean | null>((resolve) => {\n execFile(\n 'codex',\n ['execpolicy', 'check', '--rules', rulesPath, ...tokens],\n { env, timeout: timeoutMs, windowsHide: true },\n (_err, stdout) => {\n // A parse error is reported on stderr WITH EXIT 0, so the exit code\n // proves nothing and the JSON on stdout is the whole answer.\n // No stdout at all: the binary is missing, too old for the\n // subcommand, or it timed out. All three are \"could not ask\".\n if (typeof stdout !== 'string' || stdout.length === 0) {\n resolve(null);\n return;\n }\n try {\n const parsed: unknown = JSON.parse(stdout);\n const decision =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { decision?: unknown }).decision\n : undefined;\n resolve(decision === 'allow');\n } catch {\n resolve(null);\n }\n },\n );\n });\n}\n\n/** A self-test with a person waiting on it; past this the answer is \"unknown\". */\nconst VERIFY_MS = 5_000;\n\n/**\n * Remove the grant entirely. `uninstall`'s half, and the only path that deletes\n * rather than narrows: an operator who removed Tenjin should keep no standing\n * permission for it, not even the free tier.\n */\nexport async function removeCodexGrant(\n home: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<{ path: string; removed: boolean }> {\n const path = codexRulesPath(home, env);\n // Only a regular file of ours. A directory or a device parked at that name\n // is not something an uninstall may delete on a pattern.\n const found = await stat(path).catch(() => null);\n if (found === null || !found.isFile()) return { path, removed: false };\n await rm(path, { force: true });\n return { path, removed: true };\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\nexport const RETIRED_SKILL_NAMES = ['tenjin-pay'] as const;\n\n/** Retired names remain known to uninstall, but are never packaged or healed. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n */\nexport const SHIPPED_SKILL_FILES: Record<\n SkillName | (typeof RETIRED_SKILL_NAMES)[number],\n readonly string[]\n> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import { AGENT_ID_RE } from '../lib/grade';\nimport { CONTEXT_MAX } from '../hooks/constants';\nimport {\n claudeSettingsPath,\n inspectClaudeGrant,\n wireFreeVerbAllowlist,\n} from '../lib/harness-permissions';\nimport { hasErrorMarker } from './error-markers';\nimport type {\n Emit,\n Event,\n HarnessAdapter,\n HookInput,\n HookTool,\n Registrar,\n ToolKind,\n ToolResult,\n} from './types';\n\n/**\n * Claude Code as a harness. Facts from https://code.claude.com/docs/en/hooks\n * (fetched 2026-09-03) and the 2.1.259 binary: the http hook body is the same\n * JSON a command hook reads on stdin; a 2xx JSON response is parsed with the\n * same output schema; non-2xx, non-JSON, connection failure or timeout is a\n * non-blocking error that lets the turn continue.\n */\n\nconst NATIVE_TO_EVENT: Record<string, Event> = {\n SessionStart: 'session.start',\n UserPromptSubmit: 'prompt',\n PreToolUse: 'tool.before',\n PostToolUse: 'tool.after',\n PostToolUseFailure: 'tool.after',\n SubagentStart: 'agent.start',\n SubagentStop: 'agent.stop',\n Stop: 'turn.end',\n};\n\n/** Native tool names per kind, spelled once (the matchers below derive from them). */\nconst TOOLS: Record<ToolKind, RegExp> = {\n web: /^WebSearch$/,\n fetch: /^WebFetch$/,\n dispatch: /^(Agent|Task)$/,\n shell: /^Bash$/,\n edit: /^(Edit|Write|MultiEdit)$/,\n read: /^Read$/,\n};\n\n/** A regex `^(A|B)$` back to the `A|B` matcher string Claude's settings want. */\nfunction matcherOf(re: RegExp): string {\n return re.source.replace(/^\\^\\(?/, '').replace(/\\)?\\$$/, '');\n}\n\nconst SESSION_START_MATCHER = 'startup|clear|compact';\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction toolKind(name: string): ToolKind | 'other' {\n for (const kind of Object.keys(TOOLS) as ToolKind[]) if (TOOLS[kind].test(name)) return kind;\n return 'other';\n}\n\n/** Claude's argument shapes onto the canonical fields; nothing else reads `tool_input`. */\nfunction canonicalTool(name: string, input: Record<string, unknown>): HookTool {\n const kind = toolKind(name);\n switch (kind) {\n case 'shell':\n return { name, kind, command: str(input.command) ?? '' };\n case 'edit':\n case 'read': {\n const path = str(input.file_path);\n return { name, kind, paths: path === undefined ? [] : [path] };\n }\n case 'dispatch': {\n const description = str(input.description);\n return {\n name,\n kind,\n task: str(input.prompt) ?? '',\n ...(description !== undefined ? { description } : {}),\n };\n }\n case 'web':\n return { name, kind, query: str(input.query) ?? '' };\n case 'fetch':\n return { name, kind, url: str(input.url) ?? '', prompt: str(input.prompt) ?? '' };\n default:\n return { name, kind };\n }\n}\n\nfunction toolResult(v: unknown): ToolResult | undefined {\n if (typeof v === 'string') return { text: v };\n if (!isRecord(v)) return undefined;\n const out: ToolResult = {};\n const stdout = str(v.stdout);\n const stderr = str(v.stderr);\n const error = str(v.error);\n if (stdout !== undefined) out.stdout = stdout;\n if (stderr !== undefined) out.stderr = stderr;\n if (error !== undefined) out.error = error;\n if (stdout === undefined && stderr === undefined && error === undefined) {\n // A Read or a WebFetch answers with text under various keys; keep one.\n const text = str(v.text) ?? str(v.content) ?? str(v.result);\n if (text !== undefined) out.text = text;\n }\n return out;\n}\n\n/**\n * Pure. Returns null for an unknown event, a missing session, or an `agent_id`\n * that is present but fails `AGENT_ID_RE`: the harness named a worker this build\n * cannot use, and recording the fire anyway would file a child's work under the\n * lead.\n */\nexport function decode(raw: unknown): HookInput | null {\n if (!isRecord(raw)) return null;\n const native = str(raw.hook_event_name);\n if (native === undefined) return null;\n const event = NATIVE_TO_EVENT[native];\n if (event === undefined) return null;\n const session = str(raw.session_id);\n if (session === undefined || session.length === 0) return null;\n\n const input: HookInput = {\n harness: 'claude',\n event,\n native: { event: native },\n session,\n cwd: str(raw.cwd) ?? '',\n raw,\n };\n if (raw.agent_id !== undefined && raw.agent_id !== null) {\n const id = raw.agent_id;\n if (typeof id !== 'string' || !AGENT_ID_RE.test(id)) return null;\n input.agent = id;\n }\n const turn = str(raw.prompt_id);\n if (turn !== undefined) input.turn = turn;\n const prompt = str(raw.prompt);\n if (prompt !== undefined) input.prompt = prompt;\n const agentType = str(raw.agent_type);\n if (agentType !== undefined) input.agentType = agentType;\n const lastMessage = str(raw.last_assistant_message);\n if (lastMessage !== undefined) input.lastMessage = lastMessage;\n if (typeof raw.stop_hook_active === 'boolean') input.stopFuse = raw.stop_hook_active;\n const source = str(raw.source);\n if (source !== undefined) input.source = source;\n const path = str(raw.transcript_path);\n const agentPath = str(raw.agent_transcript_path);\n if (path !== undefined || agentPath !== undefined) {\n input.transcript = {};\n if (path !== undefined) input.transcript.path = path;\n if (agentPath !== undefined) input.transcript.agentPath = agentPath;\n }\n\n if (event === 'tool.before' || event === 'tool.after') {\n const name = str(raw.tool_name) ?? '';\n const tool: HookTool = canonicalTool(name, isRecord(raw.tool_input) ? raw.tool_input : {});\n const callId = str(raw.tool_use_id);\n if (callId !== undefined) tool.callId = callId;\n if (event === 'tool.after') {\n // Decided here, never by an arm reading the text: PostToolUseFailure is\n // a distinct event literal in the 2.1.259 schema, and a Bash PostToolUse\n // whose output carries an error marker is a failure too (decision 9):\n // a non-zero exit inside a pipe, or a runner that prints its verdict and\n // exits zero, arrives as a plain PostToolUse.\n if (native === 'PostToolUseFailure') {\n tool.ok = false;\n if (typeof raw.error === 'string') tool.result = { error: raw.error };\n else {\n const result = toolResult(raw.error);\n if (result !== undefined) tool.result = result;\n }\n } else {\n const result = toolResult(raw.tool_response);\n if (result !== undefined) tool.result = result;\n tool.ok = !(\n tool.kind === 'shell' &&\n hasErrorMarker((result?.stdout ?? '') + '\\n' + (result?.stderr ?? ''))\n );\n }\n if (typeof raw.is_interrupt === 'boolean') tool.interrupted = raw.is_interrupt;\n }\n input.tool = tool;\n }\n return input;\n}\n\n/**\n * Pure. `null` when there is nothing to say (the daemon answers 204).\n *\n * ONE FIELD FOR EVERY EVENT. On Stop and SubagentStop `additionalContext` keeps\n * the conversation going through the same loop protections `decision: 'block'`\n * would, and reads in the transcript as hook feedback rather than a hook error\n * (https://code.claude.com/docs/en/hooks, checked 2026-09-06), so the turn-end\n * ask travels the same way a lookup's context does.\n */\nexport function encode(emit: Emit | null, input: HookInput): unknown {\n if (emit === null || emit.context === undefined || emit.context.length === 0) return null;\n return {\n hookSpecificOutput: {\n hookEventName: input.native.event,\n additionalContext: emit.context.slice(0, CONTEXT_MAX),\n },\n };\n}\n\n/** One settings.json handler, as `install` writes it (PR C). */\nfunction httpHandler(url: string, token: string, timeoutSeconds: number) {\n // The token is a literal: Claude Code interpolates `$VAR` only from its own\n // environment and only for names in `allowedEnvVars`, which nothing exports.\n return {\n type: 'http',\n url,\n headers: { Authorization: `Bearer ${token}` },\n timeout: timeoutSeconds,\n };\n}\n\nfunction commandHandler(shimPath: string, timeoutSeconds: number) {\n return {\n type: 'command',\n command: `node ${JSON.stringify(shimPath)} --harness claude`,\n timeout: timeoutSeconds,\n };\n}\n\nexport const registrar: Registrar = {\n configPath(home) {\n return claudeSettingsPath(home);\n },\n /**\n * 9 `http` entries and 2 `command` entries (02-redesign.md §4). SessionStart\n * and UserPromptSubmit run the shim because every turn begins with a prompt:\n * the daemon is then up before any tool-path fire of that turn.\n */\n plan({ url, token, shimPath, timeoutSeconds }) {\n const http = [httpHandler(url, token, timeoutSeconds)];\n const command = [commandHandler(shimPath, timeoutSeconds)];\n return [\n { event: 'SessionStart', matcher: SESSION_START_MATCHER, hooks: command },\n { event: 'UserPromptSubmit', hooks: command },\n // ONE entry for both web kinds. The arms are separate; the harness entry\n // is not, because a settings file with two PreToolUse entries whose\n // matchers overlap is two POSTs for one tool call.\n {\n event: 'PreToolUse',\n matcher: `${matcherOf(TOOLS.web)}|${matcherOf(TOOLS.fetch)}`,\n hooks: http,\n },\n { event: 'PreToolUse', matcher: matcherOf(TOOLS.dispatch), hooks: http },\n {\n event: 'PreToolUse',\n matcher: `${matcherOf(TOOLS.edit)}|${matcherOf(TOOLS.shell)}`,\n hooks: http,\n },\n { event: 'PostToolUse', matcher: matcherOf(TOOLS.shell), hooks: http },\n { event: 'PostToolUse', matcher: matcherOf(TOOLS.read), hooks: http },\n { event: 'PostToolUseFailure', matcher: matcherOf(TOOLS.shell), hooks: http },\n { event: 'SubagentStart', hooks: http },\n { event: 'SubagentStop', hooks: http },\n { event: 'Stop', hooks: http },\n ];\n },\n grant: {\n path: claudeSettingsPath,\n inspect: inspectClaudeGrant,\n write: wireFreeVerbAllowlist,\n },\n};\n\nexport const claudeAdapter: HarnessAdapter = { id: 'claude', decode, encode, registrar };\n","import { join } from 'node:path';\nimport { codexRulesPath, removeCodexGrant } from '../lib/codex-rules';\nimport { inspectCodexGrant, wireCodexGrant } from '../lib/harness-permissions';\nimport { readCodexTrust, trustCodexHooks } from '../lib/codex-trust';\nimport type { HarnessAdapter, Registrar } from './types';\n\nimport { decode, encode, SHELL_TOOL, PATCH_TOOL } from './codex-wire';\nexport { decode, encode, patchPaths } from './codex-wire';\n\nimport { codexHome } from '../lib/codex-home';\nexport { codexHome } from '../lib/codex-home';\n\nfunction commandHandler(shimPath: string, timeoutSeconds: number) {\n return {\n type: 'command',\n command: `node ${JSON.stringify(shimPath)} --harness codex`,\n timeout: timeoutSeconds,\n };\n}\n\nexport const registrar: Registrar = {\n configPath(home, env) {\n return join(codexHome(home, env), 'hooks.json');\n },\n /**\n * Seven `command` entries, every one through the shim: a Codex handler\n * carries no URL or token, so the daemon is ensured on each fire and the\n * entry holds nothing worth protecting. The matchers are the two hooked\n * tool names the arms read; a child's fires arrive through the same entries.\n */\n plan({ shimPath, timeoutSeconds }) {\n const command = [commandHandler(shimPath, timeoutSeconds)];\n return [\n { event: 'SessionStart', hooks: command },\n { event: 'UserPromptSubmit', hooks: command },\n { event: 'PreToolUse', matcher: `${SHELL_TOOL}|${PATCH_TOOL}`, hooks: command },\n { event: 'PostToolUse', matcher: SHELL_TOOL, hooks: command },\n { event: 'SubagentStart', hooks: command },\n { event: 'SubagentStop', hooks: command },\n { event: 'Stop', hooks: command },\n ];\n },\n /**\n * Codex reads hooks once, at session start. `install` now trusts the entries\n * it writes through Codex's own supported path (lib/codex-trust.ts), so the\n * `/hooks` walkthrough this used to carry is gone; what is left is the one\n * fact no installer can change, which is that the session already open still\n * has the hook set it started with (tenjin-agent#343).\n */\n activation() {\n return ['Start a new Codex session: hooks are read at session start.'];\n },\n grant: {\n path: codexRulesPath,\n inspect: inspectCodexGrant,\n write: wireCodexGrant,\n remove: removeCodexGrant,\n },\n trust: {\n ensure: trustCodexHooks,\n read: readCodexTrust,\n },\n};\n\nexport const codexAdapter: HarnessAdapter = { id: 'codex', decode, encode, registrar };\n","import { withAppServer } from './codex-app-server';\nimport { join } from 'node:path';\nimport { codexHome } from './codex-home';\n\n/**\n * What Codex says about the hook handlers this CLI registered, and the one\n * write that makes them run: `doctor` needs to tell \"the file exists\" from\n * \"the harness will run it\", and `install` needs to move it from the first to\n * the second.\n *\n * Codex gates a handler on `[hooks.state]` in `$CODEX_HOME/config.toml`: a row keyed\n * `\"<source path>:<event_snake>:<group>:<handler>\"` carrying `enabled` and a\n * `trusted_hash`, and the handler runs only when it is enabled and that hash\n * still matches the one Codex recomputes from the file.\n *\n * TRUSTING IS PART OF INSTALLING, and it goes through Codex's own supported\n * path: read the rows and their `currentHash` from `hooks/list`, upsert those\n * keys through `config/batchWrite`, then list again and require them back\n * trusted. That is the same call the `/hooks` browser makes, and it matches\n * Claude Code's contract that installing a hook activates it, rather than\n * reporting success over a loop that cannot run (tenjin-agent#342/#343).\n *\n * WHAT STAYS FORBIDDEN, and the distinction is the whole of the boundary:\n *\n * - COMPUTING a `trusted_hash`. The value is a normalized, TOML-projected,\n * canonical-JSON form private to Codex's build. We only ever echo back the\n * `currentHash` Codex itself just reported, so trust cannot outlive the\n * bytes Codex hashed. A hash of our own would be an assertion about a file\n * Codex has not read.\n * - Trusting a row we did not generate. Every key is matched against the\n * complete handler identity this install wrote: our source file, our\n * command, our event and index. Another tool's entry in the same file is\n * never touched.\n * - Reporting success on a partial result. Listing, writing and verifying all\n * have to land, or the install fails and says which step did not.\n */\n\n/** Codex's snake-case event labels, in the order its `hooks.state` keys use. */\nconst EVENT_LABEL: Readonly<Record<string, string>> = {\n PreToolUse: 'pre_tool_use',\n PermissionRequest: 'permission_request',\n PostToolUse: 'post_tool_use',\n PreCompact: 'pre_compact',\n PostCompact: 'post_compact',\n SessionStart: 'session_start',\n SessionEnd: 'session_end',\n UserPromptSubmit: 'user_prompt_submit',\n SubagentStart: 'subagent_start',\n SubagentStop: 'subagent_stop',\n Stop: 'stop',\n Interrupt: 'interrupt',\n};\n\n/** `$CODEX_HOME/config.toml`, the file that carries `[hooks.state]`. */\nexport function codexConfigPath(home: string, env: NodeJS.ProcessEnv = process.env): string {\n return join(codexHome(home, env), 'config.toml');\n}\n\n/**\n * The trust state of the handlers we registered.\n *\n * - `trusted`: Codex will run them, all enabled and trusted or managed.\n * - `modified`: trusted once, file changed since, so Codex refuses them. The\n * state a \"is there a row for it\" reader gets wrong, which is why this\n * module asks Codex rather than the file.\n * - `untrusted` / `partial`: none, or only some, reviewed.\n * - `disabled`: reviewed and turned off.\n * - `unknown`: could not be asked. Never good news, never bad news.\n */\nexport type CodexTrust = 'trusted' | 'modified' | 'untrusted' | 'partial' | 'disabled' | 'unknown';\n\nexport interface CodexTrustReport {\n state: CodexTrust;\n /** How the answer was obtained, because they are not equally strong. */\n source: 'app-server' | 'none';\n /** The file the state lives in, named whatever the answer is. */\n configPath: string;\n /** Handlers of ours Codex will actually run. */\n trusted: number;\n /** Handlers of ours we asked about. */\n expected: number;\n}\n\n/**\n * The `[hooks.state]` key for one handler: source file, the event's snake\n * label, and its position in that event's list (`hooks/src/lib.rs`). The\n * indices have to come from the file as written, not from the plan, because a\n * hand-merged entry ahead of ours shifts them.\n */\nexport function trustKey(\n hooksPath: string,\n event: string,\n groupIndex: number,\n handlerIndex: number,\n): string | null {\n const label = EVENT_LABEL[event];\n return label === undefined ? null : `${hooksPath}:${label}:${groupIndex}:${handlerIndex}`;\n}\n\n/** One handler as `hooks/list` reports it; every field optional, since this is\n * another program's wire format and a missing one means \"cannot tell\". */\ninterface ListedHook {\n key?: unknown;\n enabled?: unknown;\n trustStatus?: unknown;\n sourcePath?: unknown;\n currentHash?: unknown;\n command?: unknown;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/**\n * Fold `hooks/list` rows for OUR keys into one verdict.\n *\n * Exported for its own tests: this is the whole of the trust judgment, and it\n * is worth pinning against recorded rows rather than only against a live\n * binary that a contributor may not have.\n */\nexport function foldTrust(rows: readonly ListedHook[], keys: readonly string[]): CodexTrust {\n const wanted = new Set(keys);\n const mine = rows.filter((r) => typeof r.key === 'string' && wanted.has(r.key));\n if (mine.length === 0) return 'untrusted';\n const status = (r: ListedHook): string =>\n typeof r.trustStatus === 'string' ? r.trustStatus : 'unknown';\n // Worst news first: each of these is a different remedy, and reporting the\n // cheerful aggregate over any one of them is how an inert install reads as\n // finished.\n if (mine.some((r) => r.enabled === false)) return 'disabled';\n if (mine.some((r) => status(r) === 'modified')) return 'modified';\n const good = mine.filter((r) => status(r) === 'trusted' || status(r) === 'managed');\n if (good.length === 0) return 'untrusted';\n if (good.length < keys.length) return 'partial';\n return 'trusted';\n}\n\nexport interface TrustProbeOptions {\n env?: NodeJS.ProcessEnv;\n /** How long to wait for the app server. Past it the answer is `unknown`. */\n timeoutMs?: number;\n /** Seam for tests: what `hooks/list` returned, without spawning anything. */\n listHooks?: (home: string, env: NodeJS.ProcessEnv) => Promise<ListedHook[] | null>;\n /** Seam for tests: answer requests directly instead of spawning an app\n * server. `undefined` from it means the same as no reply. */\n connect?: (method: string, params: unknown) => Promise<unknown>;\n}\n\n/**\n * A doctor probe has a person waiting and a daemon it has not yet checked, so\n * the app server gets a few seconds and no more. A slow answer is `unknown`,\n * which reads as \"could not ask\" and never as a verdict.\n */\nconst PROBE_MS = 8_000;\n\n/**\n * One app-server connection, for the length of `fn`.\n *\n * NEVER LEAVES A SERVER BEHIND: the handshake goes in, `fn` issues whatever\n * requests it needs on the same connection, and the process has its stdin\n * closed and is killed on every exit path including a throw. Trusting needs\n * three round trips (list, write, list again) and they must see the same\n * process, so a one-shot helper per request would not do.\n *\n * Resolves null when the connection cannot be had at all: no `codex`, a build\n * without the method, a handshake that timed out. Null is \"could not ask\", and\n * no caller may read it as an answer.\n */\n/** `hooks/list`, or null when the connection could not be had. */\nasync function listHooksViaAppServer(\n home: string,\n env: NodeJS.ProcessEnv,\n timeoutMs: number,\n): Promise<ListedHook[] | null> {\n return await withAppServer(home, env, timeoutMs, async (request) => {\n const result = await request('hooks/list', { cwds: [] });\n return result === undefined ? null : rowsOf(result);\n });\n}\n\n/** The handler rows out of a `hooks/list` result, flattened across its cwds. */\nfunction rowsOf(result: unknown): ListedHook[] {\n if (!isRecord(result) || !Array.isArray(result.data)) return [];\n const out: ListedHook[] = [];\n for (const group of result.data) {\n if (!isRecord(group) || !Array.isArray(group.hooks)) continue;\n for (const hook of group.hooks) if (isRecord(hook)) out.push(hook as ListedHook);\n }\n return out;\n}\n\n/** What one trust attempt did, in the terms `install` reports it. */\nexport interface TrustResult {\n ok: boolean;\n /** Keys Codex confirmed enabled and trusted on the verifying read. */\n trusted: string[];\n /** Which step did not complete, on a failure. */\n failedAt?: 'list' | 'write' | 'verify';\n /** One line naming what went wrong, for the operator. */\n reason?: string;\n}\n\n/**\n * Trust exactly the handlers this install wrote, and prove it.\n *\n * THREE ROUND TRIPS, ALL REQUIRED. List to learn the hashes Codex computed for\n * OUR rows; upsert only those keys; list again and require the same keys back\n * with the same hashes, enabled and trusted. The verifying read is the point:\n * a write that returned without error still has not been shown to have taken\n * effect, and an install that skipped this could report success over a loop\n * that will not run, which is the failure this whole change exists to end.\n *\n * `ownedBy` is the second half of \"only our rows\". The keys already come from\n * the file we wrote, but a key is a path and two indices; this also requires\n * the listed handler's command to be the one we generated, so a row that moved\n * under our key is left alone rather than trusted on its position.\n */\nexport async function trustCodexHooks(\n home: string,\n keys: readonly string[],\n ownedBy: (row: { command?: unknown; sourcePath?: unknown }) => boolean,\n opts: TrustProbeOptions = {},\n): Promise<TrustResult> {\n const env = opts.env ?? process.env;\n const timeoutMs = opts.timeoutMs ?? PROBE_MS;\n if (keys.length === 0) return { ok: true, trusted: [] };\n\n const run = async (\n request: (method: string, params: unknown) => Promise<unknown>,\n ): Promise<TrustResult> => {\n const before = await request('hooks/list', { cwds: [] });\n if (before === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: 'hooks/list did not answer',\n };\n }\n const wanted = new Set(keys);\n const mine = rowsOf(before).filter(\n (r) => typeof r.key === 'string' && wanted.has(r.key) && ownedBy(r),\n );\n if (mine.length !== keys.length) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: `Codex listed ${mine.length} of the ${keys.length} entries this install wrote`,\n };\n }\n // Only the rows we generated, each carrying the hash Codex just reported\n // for it. `upsert` leaves every other row in `hooks.state` untouched.\n const value: Record<string, { trusted_hash: string; enabled: true }> = {};\n for (const row of mine) {\n const hash = typeof row.currentHash === 'string' ? row.currentHash : null;\n if (hash === null) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: 'Codex reported an entry with no currentHash',\n };\n }\n value[row.key as string] = { trusted_hash: hash, enabled: true };\n }\n const wrote = await request('config/batchWrite', {\n edits: [{ keyPath: 'hooks.state', value, mergeStrategy: 'upsert' }],\n reloadUserConfig: true,\n });\n if (wrote === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'write' as const,\n reason: 'config/batchWrite was refused',\n };\n }\n\n // VERIFY. Same keys, same hashes, enabled and trusted, read back from the\n // binary rather than inferred from a write that did not error.\n const after = await request('hooks/list', { cwds: [] });\n if (after === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'verify' as const,\n reason: 'the verifying hooks/list did not answer',\n };\n }\n const confirmed = rowsOf(after).filter(\n (r) =>\n typeof r.key === 'string' &&\n wanted.has(r.key) &&\n ownedBy(r) &&\n r.enabled !== false &&\n (r.trustStatus === 'trusted' || r.trustStatus === 'managed') &&\n r.currentHash === value[r.key]?.trusted_hash,\n );\n if (confirmed.length !== keys.length) {\n return {\n ok: false,\n trusted: confirmed.map((r) => r.key as string),\n failedAt: 'verify' as const,\n reason: `Codex confirmed ${confirmed.length} of ${keys.length} entries as trusted after the write`,\n };\n }\n return { ok: true, trusted: confirmed.map((r) => r.key as string) };\n };\n\n const outcome =\n opts.connect !== undefined\n ? await run(opts.connect)\n : await withAppServer(home, env, timeoutMs, run);\n\n return (\n outcome ?? {\n ok: false,\n trusted: [],\n failedAt: 'list',\n reason: 'the codex app server could not be reached',\n }\n );\n}\n\n/**\n * What Codex will do with our hooks. `keys` comes from the caller reading the\n * installed hooks.json, so an empty list is \"nothing of ours is registered\"\n * and answers `unknown` rather than inventing a verdict.\n */\nexport async function readCodexTrust(\n home: string,\n keys: readonly string[],\n opts: TrustProbeOptions = {},\n): Promise<CodexTrustReport> {\n const env = opts.env ?? process.env;\n const configPath = codexConfigPath(home, env);\n const base = { configPath, trusted: 0, expected: keys.length };\n if (keys.length === 0) return { ...base, state: 'unknown', source: 'none' };\n\n const list = await (\n opts.listHooks ?? ((h, e) => listHooksViaAppServer(h, e, opts.timeoutMs ?? PROBE_MS))\n )(home, env);\n if (list !== null) {\n const state = foldTrust(list, keys);\n const wanted = new Set(keys);\n const trusted = list.filter(\n (r) =>\n typeof r.key === 'string' &&\n wanted.has(r.key) &&\n (r.trustStatus === 'trusted' || r.trustStatus === 'managed'),\n ).length;\n return { ...base, trusted, state, source: 'app-server' };\n }\n\n // Trust is Codex's judgment over its private handler hash. If Codex cannot be\n // asked, a config.toml row cannot settle whether that hash still matches.\n return { ...base, state: 'unknown', source: 'none' };\n}\n","import { claudeAdapter } from './claude';\nimport { codexAdapter } from './codex';\nimport type { Harness, HarnessAdapter } from './types';\n\n/**\n * The adapters this build implements, spelled once: the daemon dispatches\n * `/hook/:harness` over it and the installer wires hook entries for the\n * members it detects. Skills-only targets (`shared`) are not here; a harness\n * joins when its adapter lands.\n */\nexport const ADAPTERS: Record<Harness, HarnessAdapter> = {\n claude: claudeAdapter,\n codex: codexAdapter,\n};\n\nexport function adapterFor(harness: string): HarnessAdapter | undefined {\n return Object.hasOwn(ADAPTERS, harness) ? ADAPTERS[harness as Harness] : undefined;\n}\n","import { chmod, lstat, readFile, realpath, stat } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { adapterFor } from '../adapters/registry';\nimport { HARNESSES, type HarnessAdapter } from '../adapters/types';\nimport { startDaemon, type DaemonDeps, type DaemonStart } from '../daemon/control';\nimport { HARNESS_MS } from '../hooks/constants';\nimport { readPid, readToken } from '../hooks/shim';\nimport { writeFileAtomic } from './atomic-json';\nimport { hooksDir, shimBundlePath } from './paths';\nimport { HOOK_TOOL } from '../router/hook-tool';\nimport { LEGACY_MCP_SERVER_NAME } from '../router/names';\n\n/**\n * Where `tenjin install` writes a harness's hook entries, and the only place\n * that decides which entry in someone else's hooks file is ours.\n *\n * ONE MECHANISM FOR EVERY HARNESS. Claude Code and Codex both keep their hooks\n * as `{ \"hooks\": { \"<Event>\": [ { matcher?, hooks: [handler] } ] } }`, so the\n * read, the ownership test, the additive merge and the removal are written\n * once here; an adapter's {@link HarnessAdapter.registrar} supplies the file,\n * the entries and any activation step, and nothing else about it is special.\n *\n * ONE WRITE, WHOLE. There is nothing to merge entry by entry: the plan is the\n * registrar's, so this module drops every entry that is ours and appends that\n * plan. A second run therefore produces a byte-identical file, which is the\n * whole of \"idempotent\".\n *\n * ORDER IS THE ONE THING TO GET RIGHT. Claude Code re-reads settings.json\n * through a file watcher, so an entry naming a daemon that is not up yet turns\n * every live session's next tool call into an `HTTP hook error`. Hence:\n * bundles, token, a healthy daemon, and ONLY THEN the hooks file, with the\n * port read out of `daemon.pid` after `/health` answered, never derived.\n *\n * OWNERSHIP IS ONE PREDICATE, {@link ownsHookEntry}, used by the writer, by\n * `uninstall` and by `doctor`. A handler is ours when its `command` names a\n * file under our hooks dir, when its `url` is the loopback hook route, or when\n * it is an `mcp_tool` call to the settings install's `x402` server's `hook` tool.\n */\n\n/** Every basename this CLI puts in the hooks dir. */\nconst OUR_HOOK_FILES: readonly string[] = ['tenjin-daemon.mjs', 'tenjin-shim.mjs'];\n\n/**\n * The router's entries are a plain command line rather than a file under our\n * hooks dir, so ownership needs this third marker. It also SWEEPS: a machine\n * that carried the daemon's shim entries or its loopback URLs still matches on\n * the two older markers, so one install replaces whatever was there.\n */\nconst OUR_HOOK_COMMAND = 'tenjin hook ';\n\n/** `http://127.0.0.1:<port>/hook/<harness>`, the only URL we ever register. */\nconst LOOP_URL_RE = new RegExp(`^http://127\\\\.0\\\\.0\\\\.1:\\\\d+/hook/(?:${HARNESSES.join('|')})$`);\n\n/** The harness's own kill budget, in the seconds a hooks entry states. */\nexport const HOOK_TIMEOUT_SECONDS = HARNESS_MS / 1000;\n\nexport type HooksSkipReason =\n | 'declined'\n | 'dry-run'\n | 'daemon-down'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read'\n | 'unwritable';\n\nexport interface HooksResult {\n /** The harness this outcome is about. */\n harness: string;\n /** Its hooks file, absent when the harness has none. */\n path?: string;\n /** Where the daemon bundles live (or would). Absent for plain command\n * entries, which run a binary on PATH and need no directory. */\n hooksDir?: string;\n /** Hook entries of ours registered after this run, or 0 on a skip. */\n entries: number;\n /** True when this run changed the file; false when it already matched. */\n wrote: boolean;\n /** The daemon the entries point at. */\n daemon?: { pid: number; port: number; version: string };\n /** The loopback URL the `http` entries carry, when the harness has any. */\n url?: string;\n /** What the operator still has to do before the harness runs the entries,\n * one line per step. Empty for a harness this CLI can activate itself. */\n activation?: string[];\n /** Entries this run got the harness to trust, where trust is a separate\n * step from writing. Absent for a harness with no such gate. */\n trusted?: number;\n skipped?: HooksSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n}\n\nfunction skip(\n reason: HooksSkipReason,\n args: { harness: string; path?: string; hooksDir?: string; warning?: string; fix?: string },\n): HooksResult {\n return {\n harness: args.harness,\n ...(args.path !== undefined ? { path: args.path } : {}),\n ...(args.hooksDir !== undefined ? { hooksDir: args.hooksDir } : {}),\n entries: 0,\n wrote: false,\n skipped: reason,\n ...(args.warning !== undefined ? { warning: args.warning } : {}),\n ...(args.fix !== undefined ? { fix: args.fix } : {}),\n };\n}\n\n/** A decision NOT to wire, shaped like a write outcome so the caller has one type. */\nexport function hooksSkipped(\n harness: string,\n homeDir: string,\n dataDir: string,\n reason: HooksSkipReason,\n env: NodeJS.ProcessEnv = process.env,\n): HooksResult {\n const adapter = adapterFor(harness);\n return skip(reason, {\n harness,\n ...(adapter !== undefined ? { path: adapter.registrar.configPath(homeDir, env) } : {}),\n hooksDir: hooksDir(dataDir),\n fix: fixFor(reason),\n });\n}\n\n/**\n * The command that turns a skip into a write. Every skipped state names one, so a\n * machine consumer reading the envelope never has to work out the remedy from\n * prose, which is the same contract a CliError's `fix` carries.\n */\nfunction fixFor(reason: HooksSkipReason): string {\n switch (reason) {\n case 'declined':\n case 'dry-run':\n return 'Wire them with `tenjin install`.';\n case 'daemon-down':\n return 'Run `tenjin daemon start`, then re-run `tenjin install`.';\n case 'changed-since-read':\n return 'Another process changed the file mid-run; re-run `tenjin install`.';\n case 'unwritable':\n return 'The daemon, its bundles and the skills are already in place; only the hooks file could not be written. Fix its permissions (or its directory’s), then re-run `tenjin install`.';\n default:\n return 'Fix the reported file, then re-run `tenjin install`.';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Is this handler ours?\n *\n * An `mcp_tool` handler is ours when it calls the router server's `hook` tool,\n * the entries `tenjin install` writes now. Before them, two shapes for two\n * transports: a `command` handler is ours when it names one of our filenames,\n * or any path under this profile's hooks dir: the filename half recognizes an install whose data dir has since moved,\n * the directory half a file we no longer have a name for. An `http` handler is\n * ours when its URL is the loopback hook route on any port: the port moves with\n * every bind, so matching on it would strand yesterday's entry in the file.\n */\nfunction ownsHandler(handler: unknown, dataDir: string): boolean {\n if (!isPlainObject(handler)) return false;\n if (handler.type === 'mcp_tool') {\n return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === HOOK_TOOL;\n }\n const url = handler.url;\n if (typeof url === 'string' && LOOP_URL_RE.test(url)) return true;\n const command = handler.command;\n if (typeof command !== 'string') return false;\n if (command.includes(OUR_HOOK_COMMAND)) return true;\n if (OUR_HOOK_FILES.some((file) => command.includes(file))) return true;\n return command.includes(hooksDir(resolve(dataDir)));\n}\n\n/** Does this entry hold a handler of ours? The question `doctor` and\n * {@link hasHooks} ask; the writers ask {@link pruneOurHandlers} instead. */\nexport function ownsHookEntry(entry: unknown, dataDir: string): boolean {\n if (!isPlainObject(entry)) return false;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return false;\n return handlers.some((h) => ownsHandler(h, dataDir));\n}\n\n/**\n * The entry with every handler of OURS removed, or null when nothing is left of\n * it. Ownership is a property of the handler, so removal has to be too: a\n * person who hand-merged ours into an entry beside their own must keep theirs.\n */\nexport function pruneOurHandlers(entry: unknown, dataDir: string): unknown | null {\n if (!isPlainObject(entry)) return entry;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return entry;\n const kept = handlers.filter((h) => !ownsHandler(h, dataDir));\n if (kept.length === handlers.length) return entry;\n return kept.length === 0 ? null : { ...entry, hooks: kept };\n}\n\n/**\n * A `hooks` object with every handler of ours pruned, and the events that lost\n * one. An event WE emptied loses its key; one that still holds someone else's\n * entry keeps it, and an array that was already empty is left as found. The\n * one prune both `install` (before it appends its plan) and `uninstall` run.\n */\nexport function pruneHooks(\n hooks: Record<string, unknown>,\n dataDir: string,\n): { next: Record<string, unknown>; removed: string[] } {\n const next: Record<string, unknown> = {};\n const removed: string[] = [];\n for (const [event, value] of Object.entries(hooks)) {\n if (!Array.isArray(value)) {\n next[event] = value;\n continue;\n }\n const kept = value.map((e) => pruneOurHandlers(e, dataDir)).filter((e) => e !== null);\n if (kept.length !== value.length) removed.push(event);\n const emptiedByUs = kept.length === 0 && value.length > 0;\n if (!emptiedByUs) next[event] = kept;\n }\n return { next, removed };\n}\n\nexport interface HooksInspection {\n path: string;\n /** The exact bytes read, so a commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n /** Every event's entries, already known to be a list: {@link inspectHooksFile}\n * refuses the file rather than hand a writer a shape it would skip. */\n hooks: Record<string, unknown[]>;\n}\n\n/** Why a hooks file cannot be written, in the terms {@link skip} renders. */\nexport interface HooksRefusal {\n reason: HooksSkipReason;\n message: string;\n path: string;\n}\n\n/**\n * Resolve and read a hooks file. Every refusal lives here, so the shape checks\n * and the write agree by construction. Symlinks are resolved before the write\n * for the same reason lib/harness-permissions.ts resolves them: committing with\n * a rename over a dotfiles-managed link would sever it.\n */\nexport async function inspectHooksFile(\n declaredPath: string,\n): Promise<HooksInspection | { refusal: HooksRefusal }> {\n const entry = await lstat(declaredPath).catch(() => null);\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return {\n refusal: {\n reason: 'unresolvable',\n path: declaredPath,\n message: `${declaredPath} could not be resolved (${(err as Error).message}); its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return {\n refusal: {\n reason: 'unreadable',\n path,\n message: `${path} could not be read (${(err as Error).message}); no hooks were registered.`,\n },\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n refusal: {\n reason: 'unparsable',\n path,\n message: `${path} is not valid JSON (${(err as Error).message}); its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n if (!isPlainObject(parsed)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} is not a JSON object; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n settings = parsed;\n }\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isPlainObject(hooksValue)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} has a \"hooks\" key that is not an object; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n // An event whose value is not a list is refused for the same reason a\n // non-object `hooks` is: a writer would copy it through untouched and\n // silently drop this event's share of the plan while the receipt still\n // counted it. A file we do not understand is left alone and reported.\n const hooks: Record<string, unknown[]> = {};\n for (const [event, list] of Object.entries(hooksValue ?? {})) {\n if (!Array.isArray(list)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} has a \"hooks.${event}\" that is not an array of entries; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n hooks[event] = list;\n }\n return { path, raw, settings, hooks };\n}\n\n/** Best-effort read of a hooks file's `hooks` object; null for anything unreadable. */\nasync function readHooksObject(path: string): Promise<Record<string, unknown> | null> {\n try {\n const parsed: unknown = JSON.parse(await readFile(path, 'utf8'));\n const hooks = isPlainObject(parsed) ? parsed.hooks : undefined;\n return isPlainObject(hooks) ? hooks : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Does this machine already carry hook entries of ours for `adapter`?\n *\n * Read-only and best-effort: an absent, unreadable or unparseable file answers\n * \"no\", never an error. `install --refresh` asks before it converges, because a\n * refresh may re-materialize what is there and must never install onto a\n * machine that never asked for it.\n */\nexport async function hasHooks(\n adapter: HarnessAdapter,\n homeDir: string,\n dataDir: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<boolean> {\n const hooks = await readHooksObject(adapter.registrar.configPath(homeDir, env));\n if (hooks === null) return false;\n for (const list of Object.values(hooks)) {\n if (!Array.isArray(list)) continue;\n if (list.some((entry) => ownsHookEntry(entry, dataDir))) return true;\n }\n return false;\n}\n\n/** A url's port, or null for anything this build cannot parse as one. */\nfunction urlPort(url: string): number | null {\n try {\n const port = Number(new URL(url).port);\n return Number.isFinite(port) && port > 0 ? port : null;\n } catch {\n return null;\n }\n}\n\n/**\n * One registered handler of ours, addressed the way a harness's own trust\n * ledger addresses it: by event and by position. The indices are READ BACK OUT\n * OF THE FILE rather than counted off the plan, because a hand-merged entry\n * ahead of ours shifts them and a trust lookup on the wrong index is worse\n * than none (lib/codex-trust.ts).\n */\nexport interface RegisteredHandler {\n event: string;\n groupIndex: number;\n handlerIndex: number;\n}\n\nexport interface RegisteredHooks {\n path: string;\n /** How many entries of ours the file carries. */\n entries: number;\n /** The port our `http` entries name, or null when none does: a `command`\n * entry carries no port, and neither does an absent file. */\n port: number | null;\n /** Every handler of ours, in file order. */\n handlers: RegisteredHandler[];\n}\n\n/**\n * What this machine has registered for `adapter`. An absent or unreadable\n * file answers zero entries, which is the same thing to every caller: nothing\n * of ours is wired here.\n */\nexport async function registeredHooks(\n adapter: HarnessAdapter,\n homeDir: string,\n dataDir: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<RegisteredHooks> {\n const path = adapter.registrar.configPath(homeDir, env);\n const hooks = await readHooksObject(path);\n const out: RegisteredHooks = { path, entries: 0, port: null, handlers: [] };\n if (hooks === null) return out;\n for (const [event, list] of Object.entries(hooks)) {\n if (!Array.isArray(list)) continue;\n list.forEach((entry, groupIndex) => {\n if (!ownsHookEntry(entry, dataDir)) return;\n out.entries += 1;\n (entry as { hooks: unknown[] }).hooks.forEach((handler, handlerIndex) => {\n // OURS ONLY, and parsed defensively even then: a handler someone\n // hand-merged beside ours may carry a relative `url` that would\n // otherwise throw ERR_INVALID_URL out of doctor.\n if (!ownsHandler(handler, dataDir)) return;\n out.handlers.push({ event, groupIndex, handlerIndex });\n if (!isPlainObject(handler) || typeof handler.url !== 'string') return;\n out.port ??= urlPort(handler.url);\n });\n });\n }\n return out;\n}\n\nexport interface WriteHooksOptions {\n adapter: HarnessAdapter;\n homeDir: string;\n dataDir: string;\n env?: NodeJS.ProcessEnv;\n /** Where the built bundles are copied from; the CLI's own dist by default. */\n bundleDir?: string;\n /** Seam for step 1-3: bundles, token, a healthy daemon. Tests inject it. */\n start?: (dataDir: string, deps: DaemonDeps) => Promise<DaemonStart>;\n /**\n * The entries to write, each `{ event, matcher?, hooks }`. Supplying them\n * makes this a PLAIN WRITE: no daemon is started, no token is read and no\n * loopback URL exists, which is what the router's two command entries need.\n * Omitting them keeps the legacy daemon path for the shelf product, whose\n * registration this release no longer loads.\n */\n plan?: unknown[];\n /** The hooks file to write, when it is not the harness's own user-level one\n * (`tenjin install --project`). Only meaningful beside `plan`. */\n settingsPath?: string;\n}\n\n/**\n * Write one harness's hook entries, whole.\n *\n * 1. copy the built files into `<dataDir>/hooks`;\n * 2. mint `daemon.token` (0600) if absent — both inside {@link startDaemon};\n * 3. stop a daemon from an older build, then ensure a healthy one;\n * 4. only then rewrite the hooks file, mode 0600, with the port read back out\n * of `daemon.pid` and the token as a literal where the plan carries one.\n *\n * Every entry of ours is dropped before the plan is appended, so a second run\n * writes nothing at all.\n */\nexport async function writeHooks(opts: WriteHooksOptions): Promise<HooksResult> {\n const { adapter, homeDir, dataDir } = opts;\n const env = opts.env ?? process.env;\n const harness = adapter.id;\n const dir = hooksDir(dataDir);\n const declaredPath = opts.settingsPath ?? adapter.registrar.configPath(homeDir, env);\n // The DECLARED path, not the one `inspectHooksFile` resolves symlinks to:\n // the harness discovers its hooks file at the declared name, so that is the\n // source path its own trust browser shows, and telling the operator to look\n // for the link's target would send them hunting for a line that is not there.\n const steps = adapter.registrar.activation?.(declaredPath);\n const activation = steps !== undefined ? { activation: steps } : {};\n\n if (opts.plan !== undefined) return writePlainEntries(opts, opts.plan, declaredPath, activation);\n\n // Steps 1-3. A daemon that will not come up is reported as a skip rather than\n // thrown: install has already written skills and permissions, and the remedy\n // is one command.\n let started: DaemonStart;\n try {\n started = await (opts.start ?? startDaemon)(dataDir, {\n ...(opts.bundleDir !== undefined ? { bundleDir: opts.bundleDir } : {}),\n // The entries this call is about to write all post to this harness's\n // route, so a running daemon that has no such route is replaced before\n // they name it, whatever its version says (tenjin-agent#342).\n requires: [harness],\n });\n } catch (err) {\n return skip('daemon-down', {\n harness,\n path: declaredPath,\n hooksDir: dir,\n warning: `${err instanceof Error ? err.message : String(err)}; no hook entry was written, so nothing points at a daemon that is not there.`,\n fix: fixFor('daemon-down'),\n });\n }\n\n // Step 4's inputs, read back rather than remembered: the pid file is what the\n // daemon itself wrote after its bind, and the token file is what every\n // transport reads.\n const pid = readPid(dataDir);\n const token = readToken(dataDir);\n if (pid === null || token === null) {\n return skip('daemon-down', {\n harness,\n path: declaredPath,\n hooksDir: dir,\n warning: `The daemon answered but left no ${pid === null ? 'daemon.pid' : 'daemon.token'} under ${dataDir}, so no hook entry could name it.`,\n fix: fixFor('daemon-down'),\n });\n }\n const url = `http://127.0.0.1:${pid.port}/hook/${harness}`;\n\n const found = await inspectHooksFile(declaredPath);\n if ('refusal' in found) {\n return skip(found.refusal.reason, {\n harness,\n path: found.refusal.path,\n hooksDir: dir,\n warning: found.refusal.message,\n fix: fixFor(found.refusal.reason),\n });\n }\n const { path, raw, settings, hooks } = found;\n\n const plan = adapter.registrar.plan({\n url,\n token,\n shimPath: shimBundlePath(dataDir),\n timeoutSeconds: HOOK_TIMEOUT_SECONDS,\n });\n const planned = new Map<string, unknown[]>();\n for (const item of plan) {\n if (!isPlainObject(item) || typeof item.event !== 'string') continue;\n const { event, ...entry } = item;\n const list = planned.get(event) ?? [];\n list.push(entry);\n planned.set(event, list);\n }\n\n // Drop, then append. An event that held only entries of ours loses its key\n // entirely unless the plan puts one back, so a file that had eleven and now\n // needs nine does not keep two empty arrays.\n const nextHooks = pruneHooks(hooks, dataDir).next;\n for (const [event, mine] of planned) {\n const kept = nextHooks[event];\n nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;\n }\n\n const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}\\n`;\n const carriesUrl = JSON.stringify(plan).includes(url);\n const result: HooksResult = {\n harness,\n path,\n hooksDir: dir,\n entries: plan.length,\n wrote: next !== raw,\n daemon: { pid: started.health.pid, port: pid.port, version: started.health.version },\n ...(carriesUrl ? { url } : {}),\n ...activation,\n };\n // Byte-identical means untouched: a re-install that would write the same file\n // does not write it at all, so nothing downstream sees an mtime move. The MODE\n // still converges, because it is the only thing guarding a daemon token this\n // file may carry as a literal and a dotfiles sync or a stray chmod can widen\n // it long after the bytes settled.\n if (next === raw) {\n await tightenFile(path);\n return result;\n }\n\n // Optimistic concurrency, as lib/harness-permissions.ts holds it: a whole-file\n // replacement built from a snapshot, over a file the harness writes too, so a\n // change that landed underneath is refused rather than erased.\n if ((await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return skip('changed-since-read', {\n harness,\n path,\n hooksDir: dir,\n warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \\`tenjin install\\`.`,\n fix: fixFor('changed-since-read'),\n });\n }\n // 0600 because the file may carry the daemon token as a literal. A write\n // that cannot land is this module's outcome to report, not an exception for\n // the CLI to render as an internal error: everything above it succeeded.\n try {\n await writeFileAtomic(path, next, { mode: 0o600 });\n } catch (err) {\n return skip('unwritable', {\n harness,\n path,\n hooksDir: dir,\n warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,\n fix: fixFor('unwritable'),\n });\n }\n return result;\n}\n\n/** Bring an already-correct hooks file back to 0600 if something widened it. */\nasync function tightenFile(path: string): Promise<void> {\n const found = await stat(path).catch(() => null);\n if (found === null || (found.mode & 0o077) === 0) return;\n await chmod(path, 0o600).catch(() => undefined);\n}\n\n/** Is the shim bundle on disk? Half of \"installed\"; the entries are the other. */\nexport async function hookBundlesPresent(dataDir: string): Promise<boolean> {\n return await stat(shimBundlePath(dataDir)).then(\n () => true,\n () => false,\n );\n}\n\n/**\n * The plain write: drop every entry of ours, append the caller's, keep every\n * other key in the file byte for byte. No daemon, no token, no port. The\n * refusals are the daemon path's own (unresolvable, unreadable, unparsable,\n * unexpected shape, changed underneath, unwritable), because a hooks file this\n * module will not write is a hooks file this module will not write.\n */\nasync function writePlainEntries(\n opts: WriteHooksOptions,\n plan: unknown[],\n declaredPath: string,\n activation: { activation?: string[] },\n): Promise<HooksResult> {\n const harness = opts.adapter.id;\n const found = await inspectHooksFile(declaredPath);\n if ('refusal' in found) {\n return skip(found.refusal.reason, {\n harness,\n path: found.refusal.path,\n warning: found.refusal.message,\n fix: fixFor(found.refusal.reason),\n });\n }\n const { path, raw, settings, hooks } = found;\n const nextHooks = pruneHooks(hooks, opts.dataDir).next;\n for (const [event, mine] of groupPlan(plan)) {\n const kept = nextHooks[event];\n nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;\n }\n const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}\\n`;\n const result: HooksResult = {\n harness,\n path,\n entries: plan.length,\n wrote: next !== raw,\n ...activation,\n };\n if (next === raw) {\n await tightenFile(path);\n return result;\n }\n if ((await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return skip('changed-since-read', {\n harness,\n path,\n warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \\`tenjin install\\`.`,\n fix: fixFor('changed-since-read'),\n });\n }\n try {\n await writeFileAtomic(path, next, { mode: 0o600 });\n } catch (err) {\n return skip('unwritable', {\n harness,\n path,\n warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,\n fix: fixFor('unwritable'),\n });\n }\n return result;\n}\n\n/** `{ event, ...entry }[]` to a map of event to entries, in plan order. */\nfunction groupPlan(plan: unknown[]): Map<string, unknown[]> {\n const planned = new Map<string, unknown[]>();\n for (const item of plan) {\n if (!isPlainObject(item) || typeof item.event !== 'string') continue;\n const { event, ...entry } = item;\n const list = planned.get(event) ?? [];\n list.push(entry);\n planned.set(event, list);\n }\n return planned;\n}\n","import type { Harness, HarnessAdapter } from '../adapters/types';\nimport { registeredHooks } from './harness-hooks';\nimport { detectHarnesses, harnessInPlay, harnessTargetDir, onPath } from './skill-wiring';\n\n/**\n * Is one adapter part of this machine's settled installation?\n *\n * An explicit install selection outranks current detection; homes predating\n * that record fall back to the harness directory/PATH probes. Registered hook\n * entries are final evidence, so config and doctor agree even if the binary or\n * home-directory marker later moves.\n */\nexport async function installedHarnessInPlay(\n adapter: HarnessAdapter,\n home: string,\n dataDir: string,\n options: {\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n requested?: readonly Harness[];\n } = {},\n): Promise<boolean> {\n const env = options.env ?? process.env;\n const which = options.which ?? ((bin: string) => onPath(bin, env));\n if (\n harnessInPlay(\n home,\n harnessTargetDir(home, adapter.id),\n detectHarnesses(home, which),\n options.requested ?? [],\n )\n ) {\n return true;\n }\n return (await registeredHooks(adapter, home, dataDir, env)).entries > 0;\n}\n","import { DEFAULT_MAX_AUTO_SPEND, DEFAULT_SESSION_BUDGET } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { CHANNEL_DEPOSIT_ATOMIC, ROUTING_FEE_ATOMIC, usd } from './fee';\n\n/**\n * THE SPEND QUESTION, ONE TEXT FOR EVERY PLACE THAT ASKS IT: the defaults, or\n * your own limits. The selector in a terminal and the question an install\n * that could not ask hands to its agent show the same words, so the agent puts\n * to the person exactly what the selector would have. The defaults hold\n * whether or not anyone answers.\n */\n\n/** The automatic router defaults, in atomic USDC: $0.25 a call, $5 a day. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: DEFAULT_MAX_AUTO_SPEND,\n sessionBudget: DEFAULT_SESSION_BUDGET,\n} as const;\n\n/** The automatic limits install writes, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** The file's own value where it names one, else the default. */\nexport function shownLimits(config: {\n maxAutoSpend?: string | undefined;\n sessionBudget?: string | undefined;\n}): RouterLimits {\n return {\n maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,\n sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget,\n };\n}\n\n/** The limits in USD. */\nexport function limitsUsd(limits: RouterLimits): { maxAutoSpend: string; sessionBudget: string } {\n return {\n maxAutoSpend: toMoney(limits.maxAutoSpend).usd,\n sessionBudget: limits.sessionBudget === 'none' ? 'none' : toMoney(limits.sessionBudget).usd,\n };\n}\n\n/** The routing fee's terms, as the selector names them. */\nexport const ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;\n\n/** The selector's own line: either answer approves the fee. */\nexport const FEE_APPROVAL = 'Either answer also approves the routing fee.';\n\nconst DEFAULTS_USD = limitsUsd(ROUTER_DEFAULTS);\n\n/** The question, for the agent to put to the person as written. */\nexport const SPEND_QUESTION = `Use the defaults ($${DEFAULTS_USD.sessionBudget} a day, $${DEFAULTS_USD.maxAutoSpend} a call) or set your own limits.`;\n\n/** The question with the fee terms either answer approves. */\nexport function spendChoiceQuestion(): string {\n return `${SPEND_QUESTION} ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;\n}\n\n/** One answer to {@link spendChoiceQuestion}, and the one command that applies it. */\nexport interface SpendOption {\n id: 'default' | 'custom';\n label: string;\n recommended: boolean;\n /** What to ask the person after they pick this option, before running `command`. */\n ask?: string[];\n /** The command the agent runs alone for this answer. */\n command: string;\n}\n\n/**\n * The two answers, each applied by the agent with one command and never by\n * the person: `install` is the install that was run (its `--project` and\n * `--no-wallet` kept), so the answer leaves every other choice as it was.\n */\nexport function spendOptions(install: string): SpendOption[] {\n return [\n { id: 'default', label: 'Use the defaults', recommended: true, command: `${install} --yes` },\n {\n id: 'custom',\n label: 'Set my own limits',\n recommended: false,\n ask: [\n 'The most Tenjin may pay in a day, in USD, or none for no daily limit',\n 'The most it may pay for one call, in USD, at least 0.25',\n ],\n command: `${install} --max-auto-spend <usd> --session-budget <usd|none>`,\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAAA,cAAa;AACtB,SAAS,eAAe;AACxB,SAAS,WAAAC,gBAAe;;;ACFxB,SAAS,OAAO,OAAO,OAAO,UAAU,UAAU,QAAAC,aAAY;AAC9D,SAAS,SAAS,QAAAC,aAAY;;;ACD9B,SAAS,gBAAgB;AACzB,SAAS,IAAI,YAAY;AACzB,SAAS,YAAY;AA0Bd,SAAS,eAAe,MAAc,MAAyB,QAAQ,KAAa;AACzF,SAAO,KAAK,UAAU,MAAM,GAAG,GAAG,SAAS,cAAc;AAC3D;AAYO,SAAS,aAAa,MAA+B;AAC1D,QAAM,IAAI,uDAAuD,KAAK,IAAI;AAC1E,QAAM,QAAQ,IAAI,CAAC;AACnB,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,CAAC,UAAU,GAAG,MAAM,MAAM,GAAG,CAAC;AACvC;AAGO,SAAS,eAAe,QAAmC;AAChE,QAAM,UAAU,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,EAAE,KAAK,IAAI;AAC9D,SAAO,wBAAwB,OAAO;AACxC;AAGO,SAAS,gBAAgB,OAAsC;AACpE,SAAO,MAAM,IAAI,YAAY,EAAE,OAAO,CAAC,MAAqB,MAAM,IAAI;AACxE;AAGO,SAAS,cAAc,OAAkC;AAC9D,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,gBAAgB,KAAK,EAAE,IAAI,cAAc;AAAA,EAC9C;AACA,SAAO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,QAAQ,IAAI,OAAO,SAAS;AAElC,QAAM,QACJ,MAAM,SAAS,WAAc,MAAM,WAAW,aAAa,MAAM,WAAW,WACxE,IAAI,MAAM,IAAI,KACd;AACN,SAAO,KAAK,KAAK,KAAK,aAAa,KAAK,CAAC,KAAK,MAAM,OAAO,IAAI,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC;AACzF;AAGA,SAAS,cAAc,KAAa,OAAwB,MAAuB;AACjF,QAAM,cAAc,iBAAiB,GAAG;AACxC,MAAI,OAAO,WAAW,KAAK,KAAK;AAChC,MAAI,gBAAgB,OAAW,SAAQ,KAAK,MAAM,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5E,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,MAAM,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AACxE;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,SAAO;AACT;","names":["mkdir","dirname","stat","join","resolve","join","stat","stat","join","dirname","join","join","join","open","decode","encode","join","join","join","isRecord","configPath","commandHandler","registrar","join","chmod","lstat","readFile","realpath","stat","isPlainObject","dataDir","lstat","realpath","readFile","isPlainObject","dataDir","isPlainObject","dataDir","settings","entry","dataDir","mkdir","dirname","mkdir"]}