tenjin-cli 0.1.0-alpha.15 → 0.1.0-alpha.17

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 (278) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +43 -310
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-2BKS2FVE.js +93 -0
  7. package/dist/chunk-2BKS2FVE.js.map +1 -0
  8. package/dist/chunk-2G2WLVHB.js +102 -0
  9. package/dist/chunk-2G2WLVHB.js.map +1 -0
  10. package/dist/chunk-2I4QTOLB.js +11 -0
  11. package/dist/chunk-2I4QTOLB.js.map +1 -0
  12. package/dist/chunk-2JGT3KDW.js +172 -0
  13. package/dist/chunk-2JGT3KDW.js.map +1 -0
  14. package/dist/chunk-2QYORQBF.js +55 -0
  15. package/dist/chunk-2QYORQBF.js.map +1 -0
  16. package/dist/chunk-35M3VITA.js +102 -0
  17. package/dist/chunk-35M3VITA.js.map +1 -0
  18. package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
  19. package/dist/chunk-3AUDA53C.js.map +1 -0
  20. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  21. package/dist/chunk-56MOAIP5.js.map +1 -0
  22. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  23. package/dist/chunk-5QHHRMRA.js +227 -0
  24. package/dist/chunk-5QHHRMRA.js.map +1 -0
  25. package/dist/{chunk-JBIKAAT3.js → chunk-5UDD5VSY.js} +8 -8
  26. package/dist/chunk-5UDD5VSY.js.map +1 -0
  27. package/dist/chunk-7QKHZQKW.js +1680 -0
  28. package/dist/chunk-7QKHZQKW.js.map +1 -0
  29. package/dist/{chunk-ZFJJ3EXC.js → chunk-AR7U7BRG.js} +550 -182
  30. package/dist/chunk-AR7U7BRG.js.map +1 -0
  31. package/dist/chunk-AUKDYPPX.js +130 -0
  32. package/dist/chunk-AUKDYPPX.js.map +1 -0
  33. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  34. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  35. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  36. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  37. package/dist/chunk-EGELTSPU.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-J5INH7WB.js +299 -0
  40. package/dist/chunk-J5INH7WB.js.map +1 -0
  41. package/dist/chunk-JLEF5WHM.js +132 -0
  42. package/dist/chunk-JLEF5WHM.js.map +1 -0
  43. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KK4YGYTV.js +808 -0
  46. package/dist/chunk-KK4YGYTV.js.map +1 -0
  47. package/dist/{chunk-CPCX67TI.js → chunk-KUBEYXSO.js} +1076 -1038
  48. package/dist/chunk-KUBEYXSO.js.map +1 -0
  49. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  50. package/dist/{chunk-NIKXHWOL.js → chunk-LJ4DMVFI.js} +16 -16
  51. package/dist/chunk-LJ4DMVFI.js.map +1 -0
  52. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  53. package/dist/chunk-MEFB5KHA.js.map +1 -0
  54. package/dist/{chunk-HPJGOLTN.js → chunk-MRGADYDD.js} +13 -8
  55. package/dist/chunk-MRGADYDD.js.map +1 -0
  56. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  57. package/dist/chunk-N35E6CM2.js.map +1 -0
  58. package/dist/chunk-O4ZNKFRU.js +366 -0
  59. package/dist/chunk-O4ZNKFRU.js.map +1 -0
  60. package/dist/chunk-PDA2BVFY.js +244 -0
  61. package/dist/chunk-PDA2BVFY.js.map +1 -0
  62. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  63. package/dist/chunk-QDD2RN7G.js +10238 -0
  64. package/dist/chunk-QDD2RN7G.js.map +1 -0
  65. package/dist/chunk-S2NRVRPF.js +171 -0
  66. package/dist/chunk-S2NRVRPF.js.map +1 -0
  67. package/dist/chunk-TGLKKLQG.js +11 -0
  68. package/dist/chunk-TGLKKLQG.js.map +1 -0
  69. package/dist/chunk-TP4D47BY.js +127 -0
  70. package/dist/chunk-TP4D47BY.js.map +1 -0
  71. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  72. package/dist/{chunk-UO22YNY4.js → chunk-U2DZISAH.js} +43 -1
  73. package/dist/chunk-U2DZISAH.js.map +1 -0
  74. package/dist/chunk-WGQVJM56.js +165 -0
  75. package/dist/chunk-WGQVJM56.js.map +1 -0
  76. package/dist/{chunk-OLWTRUTS.js → chunk-WLMJE3GJ.js} +35 -16
  77. package/dist/chunk-WLMJE3GJ.js.map +1 -0
  78. package/dist/chunk-WS4JA6TC.js +137 -0
  79. package/dist/chunk-WS4JA6TC.js.map +1 -0
  80. package/dist/chunk-WXC57XGG.js +29 -0
  81. package/dist/chunk-WXC57XGG.js.map +1 -0
  82. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  83. package/dist/chunk-XZOEUYMX.js +1784 -0
  84. package/dist/chunk-XZOEUYMX.js.map +1 -0
  85. package/dist/{cli-KKRKBU5T.js → cli-VHYYYYXM.js} +303 -374
  86. package/dist/cli-VHYYYYXM.js.map +1 -0
  87. package/dist/config-5ADBAAXU.js +42 -0
  88. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  89. package/dist/doctor-Q35VQW3S.js +436 -0
  90. package/dist/doctor-Q35VQW3S.js.map +1 -0
  91. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  92. package/dist/{chunk-KAJZHIQ4.js → fund-GDDPL2BB.js} +81 -24
  93. package/dist/fund-GDDPL2BB.js.map +1 -0
  94. package/dist/hook-command-PBERPRE3.js +763 -0
  95. package/dist/hook-command-PBERPRE3.js.map +1 -0
  96. package/dist/index.js +8 -3
  97. package/dist/index.js.map +1 -1
  98. package/dist/install-OKDKGUXM.js +60 -0
  99. package/dist/install-wallet-SI4LZ73K.js +106 -0
  100. package/dist/install-wallet-SI4LZ73K.js.map +1 -0
  101. package/dist/{run-XYTQ5TWQ.js → mcp-XX3WRQEZ.js} +3766 -10677
  102. package/dist/mcp-XX3WRQEZ.js.map +1 -0
  103. package/dist/paths-P2N4JTDZ.js +49 -0
  104. package/dist/pay-3SYKHKWJ.js +39 -0
  105. package/dist/redact-6W23GGJC.js +15 -0
  106. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  107. package/dist/{send-G746D7PQ.js → send-LQRKTEJT.js} +29 -29
  108. package/dist/send-LQRKTEJT.js.map +1 -0
  109. package/dist/{chunk-QZ6ROAJU.js → skill-placement-JMDPSKE6.js} +155 -10
  110. package/dist/skill-placement-JMDPSKE6.js.map +1 -0
  111. package/dist/status-FFC6FO72.js +64 -0
  112. package/dist/status-FFC6FO72.js.map +1 -0
  113. package/dist/status-line-SAXSU6CR.js +87 -0
  114. package/dist/status-line-SAXSU6CR.js.map +1 -0
  115. package/dist/status-line-wiring-L2WYIYBM.js +29 -0
  116. package/dist/tenjin-daemon.mjs +20421 -0
  117. package/dist/tenjin-shim.mjs +251 -0
  118. package/dist/tenjin-vitest-reporter.mjs +49 -0
  119. package/dist/uninstall-OACH27UV.js +147 -0
  120. package/dist/uninstall-OACH27UV.js.map +1 -0
  121. package/dist/{update-R76LHOZW.js → update-4W6EKLGZ.js} +132 -16
  122. package/dist/update-4W6EKLGZ.js.map +1 -0
  123. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  124. package/dist/wallet-BMEXRR3P.js +32 -0
  125. package/dist/wallet-kdf-worker.mjs +980 -0
  126. package/docs/agent-permissions.md +71 -352
  127. package/docs/safety-model.md +16 -6
  128. package/package.json +8 -7
  129. package/LICENSE +0 -21
  130. package/dist/buy-VIRNSYGN.js +0 -47
  131. package/dist/chunk-2MYQN7HM.js +0 -247
  132. package/dist/chunk-2MYQN7HM.js.map +0 -1
  133. package/dist/chunk-2RF2GIJQ.js +0 -1188
  134. package/dist/chunk-2RF2GIJQ.js.map +0 -1
  135. package/dist/chunk-3GL2Z5QK.js +0 -57
  136. package/dist/chunk-3GL2Z5QK.js.map +0 -1
  137. package/dist/chunk-47PP7TAG.js.map +0 -1
  138. package/dist/chunk-4CQIDQOT.js +0 -167
  139. package/dist/chunk-4CQIDQOT.js.map +0 -1
  140. package/dist/chunk-4KG27W2S.js +0 -614
  141. package/dist/chunk-4KG27W2S.js.map +0 -1
  142. package/dist/chunk-5QQTYWEU.js +0 -199
  143. package/dist/chunk-5QQTYWEU.js.map +0 -1
  144. package/dist/chunk-65DTCCJ7.js +0 -21
  145. package/dist/chunk-65DTCCJ7.js.map +0 -1
  146. package/dist/chunk-A5DKHMUN.js +0 -173
  147. package/dist/chunk-A5DKHMUN.js.map +0 -1
  148. package/dist/chunk-B63XPWQ4.js +0 -246
  149. package/dist/chunk-B63XPWQ4.js.map +0 -1
  150. package/dist/chunk-CAR6FHK6.js +0 -105
  151. package/dist/chunk-CAR6FHK6.js.map +0 -1
  152. package/dist/chunk-CPCX67TI.js.map +0 -1
  153. package/dist/chunk-CQBVCYI2.js +0 -162
  154. package/dist/chunk-CQBVCYI2.js.map +0 -1
  155. package/dist/chunk-DBU5CXBV.js +0 -4731
  156. package/dist/chunk-DBU5CXBV.js.map +0 -1
  157. package/dist/chunk-DHJD77OW.js +0 -81
  158. package/dist/chunk-DHJD77OW.js.map +0 -1
  159. package/dist/chunk-EDZSNPE5.js +0 -35
  160. package/dist/chunk-EDZSNPE5.js.map +0 -1
  161. package/dist/chunk-EFWZPUTC.js +0 -65
  162. package/dist/chunk-EFWZPUTC.js.map +0 -1
  163. package/dist/chunk-EPFL6CTE.js +0 -448
  164. package/dist/chunk-EPFL6CTE.js.map +0 -1
  165. package/dist/chunk-GHLVXVZD.js +0 -142
  166. package/dist/chunk-GHLVXVZD.js.map +0 -1
  167. package/dist/chunk-H3SOOJ2I.js +0 -580
  168. package/dist/chunk-H3SOOJ2I.js.map +0 -1
  169. package/dist/chunk-HPJGOLTN.js.map +0 -1
  170. package/dist/chunk-HRGBS2PA.js +0 -203
  171. package/dist/chunk-HRGBS2PA.js.map +0 -1
  172. package/dist/chunk-ITUXPJIS.js +0 -314
  173. package/dist/chunk-ITUXPJIS.js.map +0 -1
  174. package/dist/chunk-JBIKAAT3.js.map +0 -1
  175. package/dist/chunk-KAJZHIQ4.js.map +0 -1
  176. package/dist/chunk-KINZ23CV.js.map +0 -1
  177. package/dist/chunk-LRYV3SK7.js +0 -235
  178. package/dist/chunk-LRYV3SK7.js.map +0 -1
  179. package/dist/chunk-M2O56UK7.js.map +0 -1
  180. package/dist/chunk-MJZZTKCC.js.map +0 -1
  181. package/dist/chunk-NIKXHWOL.js.map +0 -1
  182. package/dist/chunk-OKDRDT74.js +0 -209
  183. package/dist/chunk-OKDRDT74.js.map +0 -1
  184. package/dist/chunk-OKYSNAS3.js +0 -2144
  185. package/dist/chunk-OKYSNAS3.js.map +0 -1
  186. package/dist/chunk-OLWTRUTS.js.map +0 -1
  187. package/dist/chunk-QQ6ELLSA.js +0 -143
  188. package/dist/chunk-QQ6ELLSA.js.map +0 -1
  189. package/dist/chunk-QZ6ROAJU.js.map +0 -1
  190. package/dist/chunk-R7RSCBI7.js +0 -794
  191. package/dist/chunk-R7RSCBI7.js.map +0 -1
  192. package/dist/chunk-SGK2B724.js +0 -67
  193. package/dist/chunk-SGK2B724.js.map +0 -1
  194. package/dist/chunk-U6VPKMGC.js +0 -390
  195. package/dist/chunk-U6VPKMGC.js.map +0 -1
  196. package/dist/chunk-UHTVXQ2O.js +0 -140
  197. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-US456VUI.js +0 -149
  200. package/dist/chunk-US456VUI.js.map +0 -1
  201. package/dist/chunk-V44J2MXV.js +0 -400
  202. package/dist/chunk-V44J2MXV.js.map +0 -1
  203. package/dist/chunk-VJQKL3YH.js +0 -216
  204. package/dist/chunk-VJQKL3YH.js.map +0 -1
  205. package/dist/chunk-VJSQSLBM.js +0 -1442
  206. package/dist/chunk-VJSQSLBM.js.map +0 -1
  207. package/dist/chunk-VYOJOX4Z.js +0 -165
  208. package/dist/chunk-VYOJOX4Z.js.map +0 -1
  209. package/dist/chunk-WY2K35OL.js +0 -269
  210. package/dist/chunk-WY2K35OL.js.map +0 -1
  211. package/dist/chunk-ZFJJ3EXC.js.map +0 -1
  212. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  213. package/dist/cli-KKRKBU5T.js.map +0 -1
  214. package/dist/config-JMRUNYE6.js +0 -37
  215. package/dist/discover-B5HF6SHM.js +0 -102
  216. package/dist/discover-B5HF6SHM.js.map +0 -1
  217. package/dist/doctor-ZBG7X66D.js +0 -32
  218. package/dist/edit-PZJIILQE.js +0 -40
  219. package/dist/fund-EUDH5KPA.js +0 -40
  220. package/dist/inspect-QC6WEQPN.js +0 -37
  221. package/dist/install-GNK2W3PI.js +0 -972
  222. package/dist/install-GNK2W3PI.js.map +0 -1
  223. package/dist/outcome-KSGWZHUS.js +0 -24
  224. package/dist/pay-BC4UICPA.js +0 -361
  225. package/dist/pay-BC4UICPA.js.map +0 -1
  226. package/dist/publish-LXWFDIKF.js +0 -42
  227. package/dist/read-JMNUQ56P.js +0 -160
  228. package/dist/read-JMNUQ56P.js.map +0 -1
  229. package/dist/run-XYTQ5TWQ.js.map +0 -1
  230. package/dist/search-TSQAB45E.js +0 -25
  231. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  232. package/dist/send-G746D7PQ.js.map +0 -1
  233. package/dist/session-JBKWMJ24.js +0 -89
  234. package/dist/session-JBKWMJ24.js.map +0 -1
  235. package/dist/skill-heal-WKD67SLJ.js +0 -92
  236. package/dist/skill-heal-WKD67SLJ.js.map +0 -1
  237. package/dist/skill-placement-RIU4AMC2.js +0 -20
  238. package/dist/skill-placement-RIU4AMC2.js.map +0 -1
  239. package/dist/uninstall-5E263VTS.js +0 -73
  240. package/dist/uninstall-5E263VTS.js.map +0 -1
  241. package/dist/update-R76LHOZW.js.map +0 -1
  242. package/dist/usdc-4VCDHFWX.js +0 -38
  243. package/dist/usdc-4VCDHFWX.js.map +0 -1
  244. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  245. package/dist/wallet-TQ7D5EQ7.js +0 -41
  246. package/dist/wallet-TQ7D5EQ7.js.map +0 -1
  247. package/dist/wallet-ZAVXWLWP.js +0 -32
  248. package/dist/wallet-ZAVXWLWP.js.map +0 -1
  249. package/docs/command-reference.md +0 -303
  250. package/skills/tenjin/SKILL.md +0 -373
  251. package/skills/tenjin-pay/SKILL.md +0 -76
  252. package/skills/tenjin-publish/SKILL.md +0 -227
  253. package/skills/tenjin-publish/references/maintain.md +0 -39
  254. package/skills/tenjin-search/SKILL.md +0 -154
  255. package/skills/tenjin-search/references/permissions.md +0 -112
  256. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  257. /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
  258. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  259. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  260. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  261. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  262. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  263. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  264. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  265. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  266. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  267. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  268. /package/dist/{ccip-ZGGWQN4X.js.map → config-5ADBAAXU.js.map} +0 -0
  269. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  270. /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  271. /package/dist/{doctor-ZBG7X66D.js.map → install-OKDKGUXM.js.map} +0 -0
  272. /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
  273. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-3SYKHKWJ.js.map} +0 -0
  274. /package/dist/{fund-EUDH5KPA.js.map → redact-6W23GGJC.js.map} +0 -0
  275. /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  276. /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
  277. /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  278. /package/dist/{search-TSQAB45E.js.map → wallet-BMEXRR3P.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/harness-permissions.ts","../src/lib/codex-rules.ts","../src/adapters/codex.ts","../src/lib/grade.ts","../src/hooks/constants.ts","../src/lib/codex-trust.ts","../src/adapters/error-markers.ts","../src/adapters/claude.ts","../src/adapters/registry.ts","../src/lib/harness-hooks.ts","../src/daemon/control.ts","../src/hooks/shim.ts"],"sourcesContent":["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 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 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 rule goes through it.\n */\nexport async function inspectAllowlistAt(\n declaredPath: string,\n rules: readonly string[],\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.allow;\n if (allowValue !== undefined && !Array.isArray(allowValue)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} has a \"permissions.allow\" 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` in one settings file, keeping every other\n * 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): Promise<AppendAllowlistResult> {\n const found = await inspectAllowlistAt(declaredPath, rules);\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, allow: [...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 '../adapters/codex';\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 { join } from 'node:path';\nimport { AGENT_ID_RE } from '../lib/grade';\nimport { CONTEXT_MAX } from '../hooks/constants';\nimport { codexRulesPath, removeCodexGrant } from '../lib/codex-rules';\nimport { inspectCodexGrant, wireCodexGrant } from '../lib/harness-permissions';\nimport { readCodexTrust, trustCodexHooks } from '../lib/codex-trust';\nimport { hasErrorMarker } from './error-markers';\nimport type { Emit, Event, HarnessAdapter, HookInput, HookTool, Registrar } from './types';\n\n/**\n * Codex CLI as a harness. Every mapping here is backed by a payload the\n * installed `codex-cli 0.153.4` sent (`fixtures/codex/README.md`, captured\n * 2026-09-08); the schema source is openai/codex at `rust-v0.153.4`.\n *\n * What is NOT mapped, on purpose: the spawn tool (`collaborationspawn_agent`)\n * carries its task as opaque ciphertext, so there is no work order to look up\n * and no dispatch handoff; a shell PostToolUse carries no exit status, so a\n * failure is known only from an error marker and success is never known; the\n * web tool (`webrun`) is hooked by this CLI but stays outside the first\n * release's scope. Each decodes as `other`, or as unknown status, never as a\n * guess.\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 SubagentStart: 'agent.start',\n SubagentStop: 'agent.stop',\n Stop: 'turn.end',\n};\n\n/** The hook-facing tool names, spelled once for the decoder and the matchers. */\nconst SHELL_TOOL = 'Bash';\nconst PATCH_TOOL = 'apply_patch';\n\n/** The events whose only continuation is `decision: block`: their response\n * schema has no `hookSpecificOutput` at all (schema.rs, StopCommandOutputWire). */\nconst BLOCK_EVENTS: ReadonlySet<Event> = new Set<Event>(['turn.end', 'agent.stop']);\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\n/** `*** Add File: p`, `*** Update File: p`, `*** Delete File: p`, `*** Move to: q`. */\nconst PATCH_PATH_RE = /^\\*\\*\\* (?:Add File|Update File|Delete File|Move to): (.+)$/;\n\n/**\n * Every path an apply_patch names, in order, once each. The patch grammar is\n * the tool's own (apply-patch/src/parser.rs); a rename names both its source\n * and its target, because both were attempted work.\n */\nexport function patchPaths(patch: string): string[] {\n const out: string[] = [];\n for (const line of patch.split('\\n')) {\n const m = PATCH_PATH_RE.exec(line.trimEnd());\n const path = m?.[1]?.trim();\n if (path !== undefined && path.length > 0 && !out.includes(path)) out.push(path);\n }\n return out;\n}\n\nfunction canonicalTool(name: string, input: Record<string, unknown>): HookTool {\n if (name === SHELL_TOOL) return { name, kind: 'shell', command: str(input.command) ?? '' };\n if (name === PATCH_TOOL)\n return { name, kind: 'edit', paths: patchPaths(str(input.command) ?? '') };\n return { name, kind: 'other' };\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`, exactly as the Claude adapter does:\n * a child this build cannot name is dropped rather than filed under the 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: 'codex',\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.turn_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 = 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 // The response is the output text and nothing else: no exit status, on\n // a nonzero exit as much as on a clean one (PostToolUse-silent-exit).\n // So a marker is the only failure evidence, and its absence is unknown.\n const text = str(raw.tool_response);\n if (text !== undefined) tool.result = { text };\n if (tool.kind === 'shell' && text !== undefined && hasErrorMarker(text)) tool.ok = false;\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 * Two envelopes, because Codex has two: context beside the turn on prompt,\n * tool and start events, and on Stop/SubagentStop only `decision: block` with\n * the words as the `reason`, which the captured sessions show continues the\n * turn and trips `stop_hook_active` on the next stop. Both wire structs deny\n * unknown fields, so nothing else rides along.\n */\nexport function encode(emit: Emit | null, input: HookInput): unknown {\n if (emit === null || emit.context === undefined || emit.context.length === 0) return null;\n const text = emit.context.slice(0, CONTEXT_MAX);\n if (BLOCK_EVENTS.has(input.event)) return { decision: 'block', reason: text };\n return { hookSpecificOutput: { hookEventName: input.native.event, additionalContext: text } };\n}\n\n/** `$CODEX_HOME`, else `~/.codex`: the same root the CLI reads its config from. */\nexport function codexHome(home: string, env: NodeJS.ProcessEnv = process.env): string {\n const override = env.CODEX_HOME;\n return override !== undefined && override.length > 0 ? override : join(home, '.codex');\n}\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 { CliError } from './errors';\n\n/**\n * Did the agent USE what a hook arm showed it? The transcript is the only place\n * that answer exists.\n *\n * The arms record what they delivered (`fires`/`legs`), and the shelf records\n * what it served, but neither can see what happened next: the finding lands as\n * additional context in the agent's turn, and from there it is either acted on\n * or it is not. Nobody reports that, so without this the loop has no measure of\n * its own precision.\n *\n * WHAT COUNTS AS EVIDENCE, and why it is only ever a TOOL INPUT. An agent that\n * says \"as the Tenjin note suggests\" in prose has said nothing checkable — the\n * words are cheap, the sentence is generated beside a hundred others, and prose\n * agreeing with an injection is exactly what an injection makes likely whether\n * or not it helped. A tool call is a decision the agent spent something on. So\n * this reads two kinds of row and no others: the `hook_additional_context`\n * attachment that carries the injection (the anchor), and every later\n * `tool_use` block's input, serialized whole so a command, an edit's new text\n * and a written file all read the same way.\n *\n * THREE VERDICTS FOR \"USED\", TWO WEAK. Explicit `tenjin read|inspect <id>`, or\n * the injected url appearing in a tool input, is the agent following the\n * pointer: that is `read`, and it counts anywhere later in the session,\n * because a piece bought twenty tool calls after it was shown is still a piece\n * the injection sold. A backtick span copied out of the injected text is much\n * weaker — it may be a command the agent would have run anyway — so it counts\n * only inside {@link SPAN_WINDOW} tool calls of the anchor, needs at least two\n * words, and is reported to the shelf as `partially_used` rather than `used`.\n * `likely` is weaker again: a command head or file basename named anywhere in\n * the note's prose, with no backticks at all, matched the same way and ranked\n * below `span` — see {@link likelyTokens}.\n *\n * A SPAN OR A LIKELY TOKEN IS EXCLUDED WHEN THE SESSION ALREADY USED IT BEFORE\n * THE INJECTION (tenjin-agent#254a). Boilerplate a machine writes into every\n * subagent work order — `CI=true pnpm format:check` and the like — will always\n * reappear in the next tool call whether or not the injection ran, so a match\n * that cannot see behind the anchor cannot tell \"copied because shown\" from\n * \"was going to type this anyway\". `judge()` is handed the {@link SPAN_WINDOW}\n * tool calls BEFORE the anchor as well as after, and a candidate already\n * present there earns no credit — matched at a token boundary, not by plain\n * substring, so a longer pre-injection token cannot erase credit for a\n * shorter genuine one. This applies to `span` and `likely` only: `read` is a\n * command naming this specific piece, which nothing pre-injection could have\n * done by coincidence.\n *\n * NOTHING IS NOT REJECTION UNTIL THE SESSION IS OVER. A row whose session is\n * still running has simply not been answered yet, and grading it `rejected`\n * would post a verdict the next tool call could contradict. So \"nothing matched\"\n * becomes `rejected` only once the session has ended — `sessions.ended_at`, or a\n * transcript nothing has written to for {@link ENDED_AFTER_MS}.\n *\n * RELAYED ROWS ANCHOR ON THE FIRST TOOL CALL. The subagent arm hands its finding\n * to a child at SubagentStart, and that text reaches no transcript at all: the\n * child is given it as its opening context, and neither the parent's file nor\n * the child's records a `hook_additional_context` row for it. So there is no\n * anchor to find, and there does not need to be — the pointer preceded every\n * call the child ever made, which makes the child's FIRST tool call evidence\n * rather than the row after the anchor. {@link gradeRelayed} judges from there,\n * inclusively, while {@link gradeInjection} keeps its exclusive `anchor + 1`.\n *\n * A relayed row also has no injected text on disk to take spans from — the arm\n * renders a title, a price and possibly a fetched body, and stores none of it —\n * so its span evidence comes from the piece's TITLE alone, which is usually no\n * spans at all. Relayed findings are therefore judged almost entirely on the\n * strong evidence (an explicit read, or the url), which is the right way round.\n * Storing the injected text is a second schema change and is not this one.\n *\n * The functions here are pure over parsed rows, except the two that touch the\n * filesystem at the bottom; the command in commands/grade.ts owns the store.\n */\n\n/** How many tool calls after the anchor a copied span may still be evidence. */\nexport const SPAN_WINDOW = 10;\n\n/** A transcript nothing has appended to for this long belongs to a session that\n * is over, whether or not a Stop hook ever stamped `ended_at` (a crashed or\n * killed harness never does). */\nexport const ENDED_AFTER_MS = 30 * 60_000;\n\n/** How many tool inputs `--explain` shows for a rejected row, and how much of\n * each: enough to see what the agent did instead, not a transcript dump. */\nconst EVIDENCE_ROWS = 3;\nconst EVIDENCE_CHARS = 200;\n\n/** A session id is used as a filename, so it is checked like one. */\nconst SESSION_ID_RE = /^[A-Za-z0-9-]{1,80}$/;\n\n/**\n * An agent id becomes a filename too (`agent-<id>.jsonl`), so it gets the same\n * treatment as a session id.\n *\n * THE ONLY DEFINITION, and every other reader takes it from here rather than\n * restating it: `prelude` interpolates it into the rendered scripts, where\n * `identityOf` and the capture ask's flag splice both read that one declaration,\n * and `publish --agent` tests against this constant directly. The splice and\n * `--agent` used to share a wider `shell-safe` copy admitting `.` and `:` on the\n * reasoning that only shell metacharacters matter in a command line: `:` is the\n * separator `agentKey` joins on, so an id carrying one keys a child's rows into\n * another child's range, and an id one reader accepts and another refuses is a\n * row that can never be graded or reported.\n */\nexport const AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The only two row kinds that decide anything; see the module note. */\nexport interface TranscriptRow {\n /** 1-based line number in the JSONL, for `--explain`. */\n line: number;\n kind: 'context' | 'tool_use';\n text: string;\n}\n\nexport interface GradeTarget {\n resourceId: string | null;\n url: string | null;\n title: string | null;\n}\n\nexport type Verdict =\n | { outcome: 'used'; by: 'read' | 'span' | 'likely'; evidence: string }\n | { outcome: 'rejected'; by: 'none'; evidence: string[] }\n | { outcome: 'unobserved'; by: 'none' }\n /** Still open: the session may yet answer, so nothing is written. */\n | { outcome: null; evidence: string[] };\n\n/**\n * The transcript, reduced to the rows that can decide a verdict.\n *\n * A malformed line is skipped rather than failing the parse: a transcript being\n * appended to while this runs can end mid-line, and one truncated row is not a\n * reason to refuse to grade a session.\n *\n * `isCompactSummary` rows are dropped. A compaction REPLAYS earlier tool calls\n * into a summary the assistant then carries, so counting them would let one\n * injection be \"used\" by the echo of a call that happened before it was shown.\n */\nexport function parseTranscript(jsonl: string): TranscriptRow[] {\n const rows: TranscriptRow[] = [];\n const lines = jsonl.split('\\n');\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i];\n if (raw === undefined || raw.length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n continue;\n }\n if (!isRecord(parsed)) continue;\n const line = i + 1;\n const attachment = parsed.attachment;\n if (isRecord(attachment) && attachment.type === 'hook_additional_context') {\n rows.push({ line, kind: 'context', text: contextText(attachment.content) });\n continue;\n }\n if (parsed.type !== 'assistant' || parsed.isCompactSummary === true) continue;\n const message = parsed.message;\n if (!isRecord(message) || !Array.isArray(message.content)) continue;\n for (const block of message.content) {\n if (!isRecord(block) || block.type !== 'tool_use') continue;\n rows.push({ line, kind: 'tool_use', text: JSON.stringify(block.input ?? null) });\n }\n }\n return rows;\n}\n\n/**\n * Where the injection landed, as an index into `rows`, or -1.\n *\n * THE FIRST MATCH, not the nearest one after the row's timestamp. The\n * `injections_shown_once` index makes one injected row per (session,\n * resourceId), so there is only ever one context row naming a given piece, and\n * matching it by content beats matching it by clock: the hook's `at` and the\n * transcript's line order are written by different processes.\n *\n * Id, then url, then title, weakest last: a title is display text that could\n * appear in an unrelated context row, so it is what is tried when the piece has\n * nothing more specific to be found by.\n */\nexport function findAnchor(rows: TranscriptRow[], target: GradeTarget): number {\n for (const needle of [target.resourceId, target.url, target.title]) {\n if (needle === null || needle.length === 0) continue;\n const at = rows.findIndex((row) => row.kind === 'context' && row.text.includes(needle));\n if (at !== -1) return at;\n }\n return -1;\n}\n\n/**\n * The backtick spans in the injected text worth looking for later: at least two\n * whitespace-separated words, deduped.\n *\n * TWO WORDS IS THE FLOOR because one is noise. A note names `pnpm`, `useEffect`\n * or a filename, the agent types the same token in the next command, and a\n * one-word rule calls that reuse — on a machine where the agent was going to\n * type it anyway. Two words is a phrase somebody copied.\n */\nexport function backtickSpans(text: string): string[] {\n const spans = new Set<string>();\n for (const match of text.matchAll(/`([^`\\n]+)`/g)) {\n const span = (match[1] ?? '').trim();\n if (span.split(/\\s+/).filter((w) => w.length > 0).length >= 2) spans.add(span);\n }\n return [...spans];\n}\n\n/** A candidate token has to carry its own punctuation to qualify — see\n * {@link likelyTokens}. */\nconst LIKELY_TOKEN_RE = /\\b[A-Za-z][A-Za-z0-9]*(?:[:_./-][A-Za-z0-9]+)+\\b/g;\nconst LIKELY_MIN_CHARS = 4;\n/** Compounds common enough in ordinary prose to look like a command or a path\n * but never are one. Not a promise of completeness — the punctuation\n * requirement in {@link LIKELY_TOKEN_RE} is what does most of the work; this\n * catches the handful of hyphenated English words that would otherwise slip\n * through it. */\nconst LIKELY_GENERIC = new Set([\n 're-run',\n 're-runs',\n 're-ran',\n 're-executes',\n 're-executed',\n 'up-to-date',\n 'well-known',\n 'self-contained',\n 'read-only',\n 'long-lived',\n 'built-in',\n 'one-word',\n 'two-word',\n 'so-called',\n 'case-by-case',\n 'pre-commit',\n 'post-commit',\n 'e.g',\n 'i.e',\n // The injection's OWN scaffolding, not anything a seller wrote: PUBLIC_OPENER,\n // CLOSING_LINE and the body fence itself (`--- tenjin-body <nonce> ---`) from\n // hooks/prose.ts land in every full-form injection, so without these three\n // `likelyTokens(fullForm(...))` always nets its own boilerplate as a\n // candidate.\n 'third-party',\n 're-verifying',\n 'tenjin-body',\n]);\n\n/**\n * Command heads and file basenames named anywhere in `text`, with no backticks\n * at all — the weaker, single-token net {@link judge} tries below `span` for a\n * note that describes a command in prose instead of quoting it\n * (tenjin-agent#254b: \"gh run rerun\" named only in a title, \"pnpm check\" named\n * only as English words, each with a tool call that actually followed it).\n *\n * CONSERVATIVE ON PURPOSE. A bare English word (\"run\", \"check\", or \"pnpm\" on\n * its own) is exactly what the two-word floor on {@link backtickSpans} already\n * excludes as noise the agent was going to type anyway; a single-token net\n * that took bare words would reopen that hole wider than the floor closes it.\n * So a candidate must carry its own internal structure — a colon, dot, slash,\n * underscore or hyphen joining two word-shaped halves, the way a subcommand\n * (`db:generate`), a filename (`ci.yml`), or a path segment does — which a\n * plain English word essentially never does, and it must be at least\n * {@link LIKELY_MIN_CHARS} long.\n *\n * BACKTICK CONTENT IS STRIPPED FIRST, so a span already tried (and ranked\n * above this) is never re-offered as weaker evidence for the same text.\n *\n * THE PIECE'S OWN ID AND URL ARE EXCLUDED. Those already have a dedicated,\n * stronger `read` verdict; re-crediting them here would rank a followed\n * pointer BELOW a copied identifier instead of above it.\n */\nexport function likelyTokens(text: string, target: GradeTarget): string[] {\n const stripped = text.replace(/`[^`\\n]+`/g, ' ');\n const tokens = new Set<string>();\n for (const match of stripped.matchAll(LIKELY_TOKEN_RE)) {\n const token = match[0];\n if (token.length < LIKELY_MIN_CHARS) continue;\n if (LIKELY_GENERIC.has(token.toLowerCase())) continue;\n // A FRAGMENT counts as the id or the url, not just an exact match: a uuid\n // is all hyphens and hex, so the token regex can walk in from the middle\n // of one (`bbbb-cccc-dddd-...`) and still name nothing but the piece the\n // `read` tier already owns.\n if (target.resourceId !== null && target.resourceId.includes(token)) continue;\n if (target.url !== null && target.url.length > 0 && target.url.includes(token)) continue;\n tokens.add(token);\n }\n return [...tokens];\n}\n\n/**\n * The verdict for one injection, given its transcript and its anchor.\n *\n * Read beats span: both may be present, and \"the agent went and read the piece\"\n * is the stronger claim, so it is the one reported.\n */\nexport function gradeInjection(\n rows: TranscriptRow[],\n anchor: number,\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n if (anchor < 0 || anchor >= rows.length) return { outcome: 'unobserved', by: 'none' };\n // EXCLUSIVE: the anchor row IS the injection, so the calls that can answer for\n // it are the ones after it. The ones BEFORE it are what a span or a likely\n // token has to clear to earn credit — see the module note on #254a. Bounded\n // to the same SPAN_WINDOW as `after`: a session's first call from an hour\n // before the injection is not \"standing boilerplate\" any more than a session's\n // fiftieth call after it is still \"the injection in view\" — both are the same\n // claim, made symmetrically.\n const before = rows\n .slice(0, anchor)\n .filter((row) => row.kind === 'tool_use')\n .slice(-SPAN_WINDOW);\n const after = rows.slice(anchor + 1).filter((row) => row.kind === 'tool_use');\n const text = rows[anchor]?.text ?? '';\n return judge(after, before, backtickSpans(text), likelyTokens(text, target), target, opts.ended);\n}\n\n/**\n * Where a relayed finding's evidence starts: the first `tool_use` row, or -1.\n *\n * The caller reports it as the anchor line under `--explain`, so a verdict on a\n * child still names the row it was read from.\n */\nexport function firstToolCall(rows: TranscriptRow[]): number {\n return rows.findIndex((row) => row.kind === 'tool_use');\n}\n\n/**\n * The verdict for a finding RELAYED to a subagent, given that child's own\n * transcript.\n *\n * INCLUSIVE OF THE FIRST CALL, and with no anchor at all — see the module note.\n * A child that made no tool calls has done nothing that could be evidence, so it\n * is `rejected` once it is over and open while it runs, exactly as an\n * unanswered main-session row is.\n */\nexport function gradeRelayed(\n rows: TranscriptRow[],\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n const calls = rows.filter((row) => row.kind === 'tool_use');\n // The title is the only injected text this row left on disk; usually it holds\n // no two-word backtick span at all, and that is the documented limit of what\n // a relayed row can be judged `span` or `likely` on. No pre-injection\n // exclusion here: the pointer preceded the child's first call, so there is no\n // \"before\" inside this transcript for anything to have leaked from.\n const title = target.title ?? '';\n return judge(calls, [], backtickSpans(title), likelyTokens(title, target), target, opts.ended);\n}\n\n/**\n * The evidence rules themselves, over whichever tool calls the caller decided\n * are eligible. Shared byte-for-byte by both verdict functions, so a relayed row\n * and a main-session row can never drift into being judged by different rules.\n *\n * Read beats span beats likely: each may be present alongside a weaker one, and\n * the strongest claim actually supported is the one reported.\n *\n * `before` is up to {@link SPAN_WINDOW} tool calls that happened in this same\n * session BEFORE the injection (empty for a relayed row, which has none). A\n * span or a likely token already present there is boilerplate the session was\n * going to write anyway, so it earns no credit here — tenjin-agent#254a.\n */\nfunction judge(\n after: TranscriptRow[],\n before: TranscriptRow[],\n spans: string[],\n likely: string[],\n target: GradeTarget,\n ended: boolean,\n): Verdict {\n const readRe = target.resourceId === null ? null : readCommandRe(target.resourceId);\n for (const row of after) {\n if (readRe !== null && readRe.test(row.text)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n if (target.url !== null && target.url.length > 0 && row.text.includes(target.url)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n }\n // A TOKEN BOUNDARY MATCH, not a substring, ON BOTH SIDES: `db:generate` is a\n // plain substring of `db:generate-types`, so a pre-injection call to the\n // latter must not erase credit for a genuine post-injection call to the\n // former (the `before` side) — but by the same logic, a post-injection call\n // to `db:generate-types` must not be credited as a hit for a note that only\n // ever named `db:generate` (the `after` side): that is the identical\n // boilerplate #254a exists to exclude, just spelled with the shorter token\n // as the candidate instead of the longer one. Plain `includes` on one side\n // and a boundary match on the other opens exactly that gap — fixed by\n // sharing one boundary test both directions (tenjin-agent#276 review round\n // 2, major). The class in the lookaround is exactly {@link\n // LIKELY_TOKEN_RE}'s own — a colon, dot, slash, underscore or hyphen still\n // extends a token, so this only rules out landing inside a longer one, not\n // a real reappearance next to punctuation.\n const atBoundary = (haystack: string, candidate: string): boolean =>\n new RegExp(`(?<![A-Za-z0-9:_./-])${escapeRe(candidate)}(?![A-Za-z0-9:_./-])`).test(haystack);\n const seenBefore = (candidate: string): boolean =>\n before.some((row) => atBoundary(row.text, candidate));\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = spans.find((span) => !seenBefore(span) && atBoundary(row.text, span));\n // Capped like every other evidence string here: the span is copied out of\n // injected text, which came off a shelf, and `--explain` prints it.\n if (hit !== undefined) return { outcome: 'used', by: 'span', evidence: cap(hit) };\n }\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = likely.find((token) => !seenBefore(token) && atBoundary(row.text, token));\n if (hit !== undefined) return { outcome: 'used', by: 'likely', evidence: cap(hit) };\n }\n const evidence = after.slice(0, EVIDENCE_ROWS).map(cap);\n return ended ? { outcome: 'rejected', by: 'none', evidence } : { outcome: null, evidence };\n}\n\n/** `7d`, `24h`, `30m` as milliseconds. Anything else is a usage error rather\n * than a silent default, so a typo cannot quietly widen or narrow a sweep. */\nexport function parseSince(text: string): number {\n const match = /^(\\d+)([dhm])$/.exec(text.trim());\n const value = match === null ? 0 : Number(match[1]);\n if (match === null || value <= 0) {\n throw new CliError('USAGE', `Invalid --since window: ${JSON.stringify(text)}`, {\n fix: 'Pass a window like 7d, 24h or 30m.',\n });\n }\n const unit = { d: 24 * 60 * 60_000, h: 60 * 60_000, m: 60_000 }[match[2] as 'd' | 'h' | 'm'];\n return value * unit;\n}\n\n/**\n * Where a session's transcript is, or WHY there is none.\n *\n * `absent` is a FACT ABOUT THE SESSION: the projects directory was listed and\n * holds no file for it. `unreadable` is a fact about this machine right now —\n * no projects directory, a home that is not mounted, a permissions change\n * mid-run — and says nothing about the session at all.\n */\nexport type TranscriptLookup =\n { kind: 'found'; path: string } | { kind: 'absent' } | { kind: 'unreadable'; reason: string };\n\n/**\n * The transcript for a session, or for one subagent of it, or why it was not\n * found.\n *\n * BY READDIR, not by mangling the cwd into a directory name. Claude Code names\n * the project directory from the working directory with a substitution this CLI\n * would have to reimplement and keep in step (and which a worktree, a symlinked\n * home or a renamed checkout each break differently); the session id is a uuid\n * and is unique across them, so one listing finds it wherever it landed.\n *\n * WITH AN AGENT ID IT IS A DIFFERENT FILE, not a different search: a subagent\n * writes to `<session>/subagents/agent-<id>.jsonl` beside the parent's\n * `<session>.jsonl`, under the same project directory. The child's tool calls\n * appear in NO parent file, so a row stamped with an agent id is answered only\n * here.\n *\n * THE TWO NEGATIVE ANSWERS ARE NOT THE SAME ANSWER, and collapsing them to\n * `null` is how a transient fault becomes permanent: the caller turns \"no\n * transcript\" into `unobserved`, `unobserved` is a verdict, and a verdict is\n * never re-graded. One run under a home directory that could not be read would\n * have closed every open row on the machine as never-seen, with no way back.\n */\nexport async function findTranscript(\n homeDir: string,\n sessionId: string,\n agentId: string | null = null,\n): Promise<TranscriptLookup> {\n // An id that cannot be a filename names no transcript in any project\n // directory, now or ever: that is absence, and it is permanent.\n if (!SESSION_ID_RE.test(sessionId)) return { kind: 'absent' };\n if (agentId !== null && !AGENT_ID_RE.test(agentId)) return { kind: 'absent' };\n const { readdir, stat } = await import('node:fs/promises');\n const { join } = await import('node:path');\n const projects = join(homeDir, '.claude', 'projects');\n let dirs: string[];\n try {\n dirs = (await readdir(projects, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch (err) {\n // A missing projects directory included: a machine where the harness has\n // never run, or has not run yet, has not told us anything about this row.\n return { kind: 'unreadable', reason: errorReason(err) };\n }\n let blocked: string | null = null;\n for (const dir of dirs) {\n const path =\n agentId === null\n ? join(projects, dir, `${sessionId}.jsonl`)\n : join(projects, dir, sessionId, 'subagents', `agent-${agentId}.jsonl`);\n try {\n if ((await stat(path)).isFile()) return { kind: 'found', path };\n } catch (err) {\n // ENOENT is the ordinary answer — the session is simply not in THIS\n // project directory, and on the child path its `<session>/` directory may\n // not exist at all (ENOENT, or ENOTDIR where a plain file sits where the\n // directory would be). Anything else is a directory that could be hiding\n // it, so the sweep can no longer claim the file is absent.\n const code = errorCode(err);\n if (code !== 'ENOENT' && code !== 'ENOTDIR') blocked ??= errorReason(err);\n }\n }\n return blocked === null ? { kind: 'absent' } : { kind: 'unreadable', reason: blocked };\n}\n\n/** Has nothing been appended to this transcript for {@link ENDED_AFTER_MS}? The\n * half of \"the session is over\" that survives a harness which never stopped\n * cleanly and so never stamped `ended_at`. Unreadable reads as NOT idle: an\n * unknown must never manufacture a `rejected`. */\nexport async function transcriptIdle(path: string, nowMs: number): Promise<boolean> {\n try {\n const { stat } = await import('node:fs/promises');\n return nowMs - (await stat(path)).mtimeMs > ENDED_AFTER_MS;\n } catch {\n return false;\n }\n}\n\n/** An errno if the platform gave one, else the message: short enough to print\n * on the one `--explain` line that says why a row was left alone. Exported so\n * the caller's own read of the file it was handed reports failures in the same\n * words this one does. */\nexport function errorReason(err: unknown): string {\n const code = errorCode(err);\n if (code !== null) return code;\n return cap(err instanceof Error ? err.message : 'unknown error');\n}\n\nfunction errorCode(err: unknown): string | null {\n return isRecord(err) && typeof err.code === 'string' ? err.code : null;\n}\n\nfunction readCommandRe(resourceId: string): RegExp {\n return new RegExp(`tenjin\\\\s+(?:read|inspect)\\\\s+${escapeRe(resourceId)}`);\n}\n\nfunction escapeRe(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction cap(row: TranscriptRow | string): string {\n const text = typeof row === 'string' ? row : row.text;\n return text.length > EVIDENCE_CHARS ? `${text.slice(0, EVIDENCE_CHARS)}…` : text;\n}\n\n/**\n * The injected text, whatever shape the attachment carried it in: a bare string,\n * an array of strings, or an array of `{ type: 'text', text }` blocks. All three\n * appear, and the anchor match only needs the words.\n */\nfunction contextText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n const parts: string[] = [];\n for (const item of content) {\n if (typeof item === 'string') parts.push(item);\n else if (isRecord(item) && typeof item.text === 'string') parts.push(item.text);\n }\n return parts.join('\\n');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * THE KERNEL'S bounds: every number the lifecycle, the store, the daemon and the\n * shim use that is not one of the two config knobs (`loop.human_wait_ms`,\n * `loop.tool_wait_ms`), each with the reason it is a constant\n * (tenjin-notes loop-redesign/02-redesign.md §7).\n *\n * AN ARM's own bounds are not here and must not be moved here: they are evidence\n * about one arm's input — a prompt's junk rules, the head a skipped row stores,\n * the shelf's own query bound — and each is only readable next to the code and\n * the measurement that justifies it. They live in `hooks/question.ts`,\n * `hooks/text.ts`, `hooks/legs/shelf.ts` and the arm files, and every one\n * carries its reason there the way these do here.\n */\n\n/** Left on every fetch so the response can be encoded and flushed before the\n * fire's own deadline lands. */\nexport const RESERVE_MS = 150;\n\n/** The gap between a fire's deadline and the harness's own kill: encode, socket\n * write, and the harness's parse. */\nexport const SLACK_MS = 500;\n\n/**\n * The harness timeout `install` stamps on every entry, in ms. A backstop only:\n * the fire's own deadline (2500 or 4000) always lands first, and a hung daemon\n * costs a session this much per fire, never a stuck turn. Derived:\n * `tool_wait_ms + SLACK_MS = 4500 -> 5 s`.\n */\nexport const HARNESS_MS = 5000;\n\n/**\n * How long the shim polls `/health` after spawning a daemon. A minimal daemon\n * measured 75 to 120 ms cold on this laptop (03-decisions.md, \"Measured\"); the\n * smoke test re-measures the real bundle against this number.\n */\nexport const SPAWN_MS = 500;\n\n/** The shim's `GET /health` budget. Loopback answers in 1 to 2 ms; anything\n * slower is a daemon mid-exit or a foreign listener. */\nexport const HEALTH_MS = 200;\n\n/**\n * After a spawn that never became healthy, no shim spawns again for this long.\n * A corrupt `loop.db` or a half-written bundle must not cost every prompt a\n * spawn plus `SPAWN_MS`. The record is the mtime of an empty `daemon.spawn`\n * file; `tenjin doctor` reads it (PR E).\n */\nexport const SPAWN_BACKOFF_MS = 60_000;\n\n/** Ledger rows older than this are deleted at the daemon's idle exit. Matches\n * Claude Code's own transcript sweep default. */\nexport const RETENTION_DAYS = 30;\n\n/** And past this many `fires` rows the oldest go regardless of age: a bound for\n * a team on default-on, not for one laptop. */\nexport const FIRES_ROW_CAP = 50_000;\n\n/** Retention runs in batches of this many rows: node 24's `node:sqlite` lacks\n * `DELETE ... LIMIT`, so it is `WHERE id IN (SELECT ... LIMIT n)` looped. */\nexport const RETENTION_BATCH = 500;\n\n/** Retention at idle exit stops after this long so a successor daemon is never\n * refused the port for longer than a shim will wait. */\nexport const RETENTION_MAX_MS = 5000;\n\n/** A request handler whose synchronous span exceeds this logs a warning: the\n * daemon serves every session on the machine from one loop. */\nexport const IDLE_SYNC_WARN_MS = 20;\n\n/** Largest hook body the daemon reads. A `tool_response` or\n * `last_assistant_message` past this is 413 and a log line. */\nexport const MAX_BODY_BYTES = 4 * 1024 * 1024;\n\n/** `daemon.log` is truncated at daemon start once it passes this. No rotation:\n * the idle exit bounds a log's lifetime already. */\nexport const LOG_TRUNCATE_BYTES = 5 * 1024 * 1024;\n\n/** After the idle timer fires this much later than armed, the laptop slept:\n * re-arm for {@link SLEEP_REARM_MS} instead of exiting under a resumed turn. */\nexport const SLEEP_GRACE_MS = 60_000;\nexport const SLEEP_REARM_MS = 120_000;\n\n/** The daemon's `busy_timeout`: the CLI writes `loop.db` rarely and briefly, so\n * a busy wait this long only ever happens at a CLI write's tail. */\nexport const DAEMON_BUSY_TIMEOUT_MS = 2000;\n\n/** `server.requestTimeout` and `headersTimeout` for the daemon's listener. */\nexport const REQUEST_TIMEOUT_MS = 10_000;\nexport const HEADERS_TIMEOUT_MS = 5000;\n\n/** The derived port range: `30000 + hash % 2000` sits below Linux's default\n * ephemeral range (32768+) and below macOS/Windows's (49152+), so a transient\n * outbound socket can never squat it. */\nexport const PORT_BASE = 30_000;\nexport const PORT_SPAN = 2000;\n\n/** Claude Code caps `additionalContext` here; both encoders slice their context to it. */\nexport const CONTEXT_MAX = 10_000;\n\n/** How long `tenjin daemon stop` waits after SIGTERM before SIGKILL. */\nexport const STOP_GRACE_MS = 3000;\n","import { spawn } from 'node:child_process';\nimport { join } from 'node:path';\nimport { codexHome } from '../adapters/codex';\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 */\nasync function withAppServer<T>(\n home: string,\n env: NodeJS.ProcessEnv,\n timeoutMs: number,\n fn: (request: (method: string, params: unknown) => Promise<unknown>) => Promise<T>,\n): Promise<T | null> {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('codex', ['app-server'], {\n env: { ...env, CODEX_HOME: codexHome(home, env) },\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n } catch {\n return null;\n }\n\n let dead = false;\n const pending = new Map<number, (value: unknown) => void>();\n const fail = (): void => {\n dead = true;\n for (const resolve of pending.values()) resolve(undefined);\n pending.clear();\n };\n child.on('error', fail);\n child.on('exit', fail);\n\n let buffered = '';\n child.stdout?.setEncoding('utf8');\n child.stdout?.on('data', (chunk: string) => {\n buffered += chunk;\n let cut = buffered.indexOf('\\n');\n while (cut !== -1) {\n const line = buffered.slice(0, cut);\n buffered = buffered.slice(cut + 1);\n cut = buffered.indexOf('\\n');\n let msg: unknown;\n try {\n msg = JSON.parse(line);\n } catch {\n continue;\n }\n if (!isRecord(msg) || typeof msg.id !== 'number') continue;\n const waiting = pending.get(msg.id);\n if (waiting === undefined) continue;\n pending.delete(msg.id);\n waiting(msg.error !== undefined ? undefined : msg.result);\n }\n });\n\n let nextId = 1;\n const send = (payload: unknown): boolean => {\n try {\n child.stdin?.write(`${JSON.stringify(payload)}\\n`);\n return true;\n } catch {\n return false;\n }\n };\n const request = async (method: string, params: unknown): Promise<unknown> => {\n if (dead) return undefined;\n const id = ++nextId;\n return await new Promise<unknown>((resolve) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n resolve(undefined);\n }, timeoutMs);\n pending.set(id, (value) => {\n clearTimeout(timer);\n resolve(value);\n });\n if (!send({ jsonrpc: '2.0', id, method, params })) {\n pending.delete(id);\n clearTimeout(timer);\n resolve(undefined);\n }\n });\n };\n\n try {\n // Load-bearing in this order: a request sent before the `initialized`\n // notification is dropped with no reply and no error.\n send({\n jsonrpc: '2.0',\n id: 1,\n method: 'initialize',\n params: { clientInfo: { name: 'tenjin', title: 'tenjin', version: '1' } },\n });\n send({ jsonrpc: '2.0', method: 'initialized', params: {} });\n return await fn(request);\n } catch {\n return null;\n } finally {\n try {\n child.stdin?.end();\n } catch {\n // Already closed.\n }\n child.kill('SIGTERM');\n }\n}\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","/**\n * What a Bash `PostToolUse` has to print to count as a failure\n * (13-pr-d-local-arms.md, decision 9). Claude Code raises `PostToolUseFailure`\n * only when the tool itself fails; a command that exits non-zero inside a pipe,\n * or a runner that prints its verdict and exits zero, arrives as a plain\n * `PostToolUse`. So the adapter scans stdout and stderr for a marker a real\n * toolchain emits, and `decode` sets `tool.ok` from it — the arm never reads\n * text to decide.\n *\n * Case-sensitive where the case IS the signal: `FAIL` is a vitest/jest/pytest\n * verdict, `fail` and `failed` are prose. The anchored patterns carry `m` so\n * they work on a whole stdout blob, and leading indentation is allowed because\n * runners indent their own output.\n */\nexport const ERROR_MARKERS: readonly RegExp[] = [\n // Test-runner verdicts. Uppercase only, and a whole word.\n /\\bFAIL\\b/,\n /AssertionError/,\n /\\b[1-9]\\d* (?:failed|failing|errors?)\\b/i,\n // `Error:`, `TypeError:`, `ReferenceError:`, `ModuleNotFoundError:` — the\n // JS and Python convention of naming the class before the colon — and the\n // lowercase `error:` that rustc, gcc, clang, esbuild and git open a\n // diagnostic line with. Line-start only: \"an error: occurred\" mid-sentence\n // is prose.\n /^[ \\t]*(?:\\w*Error|error):/m,\n /Traceback \\(most recent call last\\)/,\n /ModuleNotFoundError|ImportError:/,\n /Cannot find module/i,\n // A code the shell or a runner states outright. Never zero.\n /exit code [1-9]\\d*/i,\n // libuv/POSIX codes: unambiguous, and the common real failures.\n /\\b(?:ENOENT|EADDRINUSE|ECONNREFUSED|EACCES|EPERM)\\b/,\n // Toolchain-specific prefixes: npm, pnpm, tsc, cargo, go, git.\n /^[ \\t]*npm ERR!/m,\n /ERR_PNPM_/,\n /error TS\\d+:/,\n /^[ \\t]*error\\[E\\d+\\]/m,\n /^[ \\t]*panic:/m,\n /^[ \\t]*fatal:/m,\n /Unhandled(?:PromiseRejection|Rejection)/,\n /segmentation fault/i,\n];\n\n/** Whether `text` carries any marker above. The whole output, no bound: the\n * body is already bounded by the daemon's request cap and each pattern is one\n * linear scan. */\nexport function hasErrorMarker(text: string): boolean {\n return ERROR_MARKERS.some((re) => re.test(text));\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 { 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';\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, or when its `url` is the loopback hook route.\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). */\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 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 * TWO SHAPES, because there are two transports. A `command` handler is ours\n * when it names one of our filenames, or any path under this profile's hooks\n * 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 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)\n return writePlainEntries(opts, opts.plan, declaredPath, dir, 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 dir: 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 hooksDir: dir,\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 hooksDir: dir,\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 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 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/** `{ 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 { randomBytes } from 'node:crypto';\nimport { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { STOP_GRACE_MS } from '../hooks/constants';\nimport {\n ensureDaemon,\n health,\n missingRoutes,\n readPid,\n readToken,\n type Health,\n type PidRecord,\n} from '../hooks/shim';\nimport { CliError } from '../lib/errors';\nimport {\n daemonBundlePath,\n daemonPidPath,\n daemonTokenPath,\n hooksDir,\n shimBundlePath,\n vitestReporterPath,\n} from '../lib/paths';\n\n/**\n * Starting, stopping and materializing the loop daemon (02-redesign.md §4a).\n *\n * Its own module rather than part of `commands/daemon.ts` because two callers\n * need it and only one of them is a command: `tenjin daemon start|stop` renders\n * it, and `install` runs it as step 1-3 of the hook cutover — the settings file\n * may not name a daemon until a healthy one answers (lib/harness-hooks.ts).\n */\n\nexport interface DaemonDeps {\n /** Where the built bundles live; the CLI's own dist by default. */\n bundleDir?: string;\n env?: NodeJS.ProcessEnv;\n spawnMs?: number;\n sleep?: (ms: number) => Promise<void>;\n kill?: (pid: number, signal: NodeJS.Signals | 0) => void;\n now?: () => number;\n /**\n * Harnesses whose hook entries this start is about to make live. A running\n * daemon with no route for one of them is replaced, whatever its version\n * says (see {@link startDaemon}).\n */\n requires?: readonly string[];\n}\n\n/**\n * How long `install` waits for a spawned daemon, as opposed to the shim's\n * `SPAWN_MS`. The shim's budget is a fraction of one hook fire and a miss\n * there costs that fire; install has a person waiting and a miss there costs\n * the whole activation, so it buys certainty with time it already has. The\n * measured cold start is 75-120 ms, so this is ~40x headroom for a laptop\n * under load (tenjin-agent#342).\n */\nexport const INSTALL_SPAWN_MS = 5_000;\n\n/**\n * Every built file that belongs in the hooks dir, and where each one goes. The\n * reporter rides with the two bundles because it is materialized the same way\n * and by the same command; it is the one of the three that is never spawned —\n * a repo's own vitest config imports it (`lib/paths.ts`).\n */\nconst BUNDLES: Readonly<Record<string, (dir: string) => string>> = {\n 'tenjin-daemon.mjs': daemonBundlePath,\n 'tenjin-shim.mjs': shimBundlePath,\n 'tenjin-vitest-reporter.mjs': vitestReporterPath,\n};\n\n/** In the built CLI this file's chunk sits in `dist/` beside the two bundles. */\nexport function defaultBundleDir(): string {\n return dirname(fileURLToPath(import.meta.url));\n}\n\n/** Copy the built files from `dist` into the hooks dir; mint the token if absent. */\nexport function installDaemonFiles(dataDir: string, bundleDir: string): { written: string[] } {\n const written: string[] = [];\n mkdirSync(hooksDir(dataDir), { recursive: true, mode: 0o700 });\n for (const [name, target] of Object.entries(BUNDLES)) {\n const src = join(bundleDir, name);\n if (!existsSync(src)) {\n throw new CliError('INTERNAL', `Daemon bundle missing: ${src}`, {\n fix: `Reinstall tenjin-cli; the package ships dist/${Object.keys(BUNDLES).join(', dist/')}.`,\n });\n }\n const dest = target(dataDir);\n // COPY ASIDE, THEN RENAME. `copyFileSync` truncates the destination and\n // refills it, so anything reading that path mid-copy — a shim spawned by a\n // live session, a `node --import` of the reporter — sees a half-written\n // file and fails on a syntax error it can do nothing about. A rename is\n // atomic, so a reader gets the old bundle or the new one and never a\n // fragment of both (tenjin-agent#342).\n // Unique per CALL, not per process: two copies running in one process (a\n // command and a test driving the same writer) shared one staging path, and\n // the second truncating it while the first renamed left a fragment at the\n // destination, which is the very outcome the rename exists to prevent.\n const staged = `${dest}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;\n copyFileSync(src, staged);\n renameSync(staged, dest);\n written.push(dest);\n }\n if (readToken(dataDir) === null) {\n writeFileSync(daemonTokenPath(dataDir), randomBytes(32).toString('hex'), { mode: 0o600 });\n written.push(daemonTokenPath(dataDir));\n }\n return { written };\n}\n\nfunction alive(pid: number, kill: NonNullable<DaemonDeps['kill']>): boolean {\n try {\n kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM, wait, SIGKILL. Returns how it ended; clears a pid file left behind. */\nexport async function stopDaemon(\n dataDir: string,\n deps: DaemonDeps = {},\n): Promise<{ state: 'stopped' | 'killed' | 'not-running' | 'unconfirmed'; pid?: number }> {\n const kill = deps.kill ?? ((pid, sig) => process.kill(pid, sig));\n const sleep = deps.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n const now = deps.now ?? (() => Date.now());\n const rec = readPid(dataDir);\n if (rec === null || !alive(rec.pid, kill)) {\n if (rec !== null) rmSync(daemonPidPath(dataDir), { force: true });\n return { state: 'not-running' };\n }\n // Signal only a process `/health` confirms is our daemon: a crash-left pid\n // file can name a reused pid, and a signal on hearsay could kill a stranger.\n // A different pid answering on the port proves the file stale, so it goes.\n // A live pid that did not answer in time is left alone AND keeps its file:\n // a busy daemon that missed one 200 ms probe must not be orphaned without\n // a record (the next start would lose the bind to it and exit quietly).\n const h = await health(rec.port);\n if (h !== null && (h.pid !== rec.pid || h.data_dir !== dataDir)) {\n rmSync(daemonPidPath(dataDir), { force: true });\n return { state: 'not-running' };\n }\n if (h === null) return { state: 'unconfirmed', pid: rec.pid };\n kill(rec.pid, 'SIGTERM');\n const until = now() + STOP_GRACE_MS;\n while (now() < until) {\n await sleep(50);\n if (!alive(rec.pid, kill)) return { state: 'stopped', pid: rec.pid };\n }\n try {\n kill(rec.pid, 'SIGKILL');\n } catch {\n // Died between the check and the kill.\n }\n rmSync(daemonPidPath(dataDir), { force: true });\n return { state: 'killed', pid: rec.pid };\n}\n\n/** Why a running daemon had to go. */\nexport type ReplaceReason = 'older-build' | 'missing-routes';\n\n/** What one start did, for whoever renders it. */\nexport interface DaemonStart {\n health: Health;\n spawned: boolean;\n /** The daemon this start replaced. */\n replaced: PidRecord | null;\n /** Why it was replaced, when one was. */\n replacedReason?: ReplaceReason;\n /** The routes the replaced daemon could not serve, on `missing-routes`. */\n missingRoutes?: string[];\n /** An older daemon that would not confirm itself and was left alone. */\n unconfirmed: number | null;\n /** Bundles and token this call wrote. */\n written: string[];\n}\n\n/**\n * Materialize the bundles, replace a daemon this build has outgrown, and return\n * only once one is healthy. Throws when nothing came up: a caller that goes on\n * to write hook entries has no daemon to point them at.\n *\n * TWO REASONS TO REPLACE, and the second is the one that bit. A version bump\n * is obvious. The other is the route table: `deps.requires` names the\n * harnesses whose entries are about to go live, and a daemon without one of\n * those routes 404s their every fire, silently. It can be on THIS build's\n * version and still be wrong, because a version says nothing about which\n * adapters the process loaded (tenjin-agent#342). A daemon too old to report\n * `harnesses` counts as serving none, which is the safe reading.\n */\nexport async function startDaemon(dataDir: string, deps: DaemonDeps = {}): Promise<DaemonStart> {\n const { written } = installDaemonFiles(dataDir, deps.bundleDir ?? defaultBundleDir());\n // A daemon from an older build keeps serving until told: the bundle on disk\n // changed only because THIS call copied it, so this call is what stops it.\n const rec = readPid(dataDir);\n const running = rec === null ? null : await health(rec.port);\n let replaced: PidRecord | null = null;\n let reason: ReplaceReason | undefined;\n let short: string[] = [];\n let unconfirmed: number | null = null;\n if (running !== null && running.data_dir === dataDir) {\n short = missingRoutes(running, deps.requires ?? []);\n const stale =\n running.version !== pkg.version\n ? ('older-build' as const)\n : short.length > 0\n ? ('missing-routes' as const)\n : undefined;\n if (stale !== undefined) {\n const stopped = await stopDaemon(dataDir, deps);\n if (stopped.state === 'stopped' || stopped.state === 'killed') {\n replaced = rec;\n reason = stale;\n } else if (stopped.state === 'unconfirmed') unconfirmed = stopped.pid ?? null;\n }\n }\n const ensured = await ensureDaemon(dataDir, {\n ...(deps.env ? { env: deps.env } : {}),\n spawnMs: deps.spawnMs ?? INSTALL_SPAWN_MS,\n ...(deps.now ? { now: deps.now } : {}),\n });\n if (!ensured.ok) {\n throw new CliError('INTERNAL', `Daemon did not start: ${ensured.reason}`, {\n fix: `Read ${join(dataDir, 'daemon.log')}; if it names a port conflict, set \\`tenjin config set loop.port <n>\\`.`,\n });\n }\n // Checked again on the daemon actually serving now: a start that reused a\n // healthy process never went through the replace branch at all, and the\n // caller needs the routes to exist, not a restart to have been attempted.\n const stillShort = missingRoutes(ensured.health, deps.requires ?? []);\n if (stillShort.length > 0) {\n throw new CliError(\n 'INTERNAL',\n `The daemon on 127.0.0.1:${ensured.health.port} (v${ensured.health.version}) has no route for ${stillShort.join(', ')}, so its hook entries would answer 404.`,\n { fix: 'Run `tenjin daemon stop`, then re-run `tenjin install`.' },\n );\n }\n return {\n health: ensured.health,\n spawned: ensured.spawned,\n replaced,\n ...(reason !== undefined ? { replacedReason: reason } : {}),\n ...(reason === 'missing-routes' ? { missingRoutes: short } : {}),\n unconfirmed,\n written,\n };\n}\n","import { spawn } from 'node:child_process';\nimport {\n appendFileSync,\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport {\n dataDir,\n daemonBundlePath,\n daemonLogPath,\n daemonPidPath,\n daemonSpawnPath,\n daemonTokenPath,\n} from '../lib/paths';\nimport { HARNESS_MS, HEALTH_MS, SLACK_MS, SPAWN_BACKOFF_MS, SPAWN_MS } from './constants';\n\n/**\n * The shim (02-redesign.md §4a): the ensure-running point and the forwarder\n * in one, bundled to `tenjin-shim.mjs` and run by the two `command` hook\n * entries (SessionStart, UserPromptSubmit) and by every other transport's\n * `--ensure`. It imports node builtins only, parses no config and opens no\n * SQLite: its whole job is `GET /health`, maybe one spawn, one POST, exit 0.\n *\n * It never runs an arm, and it never fails the harness: every failure is one\n * `daemon-down` line in `daemon.log`, nothing on stdout, exit 0.\n */\n\nexport interface PidRecord {\n pid: number;\n port: number;\n started_at: number;\n data_dir: string;\n}\n\nexport interface Health {\n version: string;\n pid: number;\n port: number;\n uptime_ms: number;\n idle_ms: number;\n data_dir: string;\n rss: number;\n /**\n * The harnesses the RUNNING process has a route for, sorted. Absent from any\n * older daemon, and that absence is the point: a version string is no proof\n * of a route table, so a build that GAINED a harness looked identical to the\n * one before it and every `/hook/<new harness>` answered 404 until someone\n * restarted by hand (tenjin-agent#342). Absent reads as \"serves nothing I\n * can name\", never as \"serves everything\".\n */\n harnesses?: string[];\n}\n\n/** The harnesses `h` has no route for, out of the ones a caller needs. */\nexport function missingRoutes(h: Health, required: readonly string[]): string[] {\n const served = new Set(Array.isArray(h.harnesses) ? h.harnesses : []);\n return required.filter((harness) => !served.has(harness));\n}\n\n/** The CLI's `dataDir` under its shim name: one resolution, so the CLI, the shim and the daemon agree on the string. */\nexport function resolveDataDir(env: NodeJS.ProcessEnv = process.env): string {\n return dataDir(env);\n}\n\nexport function readPid(dataDir: string): PidRecord | null {\n try {\n const raw = JSON.parse(readFileSync(daemonPidPath(dataDir), 'utf8')) as Partial<PidRecord>;\n if (\n typeof raw.pid === 'number' &&\n typeof raw.port === 'number' &&\n typeof raw.started_at === 'number' &&\n typeof raw.data_dir === 'string'\n ) {\n return { pid: raw.pid, port: raw.port, started_at: raw.started_at, data_dir: raw.data_dir };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nexport function readToken(dataDir: string): string | null {\n try {\n const t = readFileSync(daemonTokenPath(dataDir), 'utf8').trim();\n return t.length > 0 ? t : null;\n } catch {\n return null;\n }\n}\n\n/** One line in `daemon.log`; the only trace a shim leaves when no daemon answers. */\nexport function logDown(dataDir: string, reason: string): void {\n try {\n mkdirSync(dataDir, { recursive: true, mode: 0o700 });\n appendFileSync(daemonLogPath(dataDir), `${new Date().toISOString()} daemon-down ${reason}\\n`);\n } catch {\n // Nowhere left to say it.\n }\n}\n\n/** `GET /health` under `timeoutMs`; null when nothing healthy answers. */\nexport async function health(port: number, timeoutMs: number = HEALTH_MS): Promise<Health | null> {\n try {\n const res = await fetch(`http://127.0.0.1:${port}/health`, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<Health>;\n if (typeof body.pid !== 'number' || typeof body.data_dir !== 'string') return null;\n return body as Health;\n } catch {\n return null;\n }\n}\n\n/**\n * The env a daemon starts with. Scrubbed: the spawning hook's env carries\n * `CLAUDE_CODE_SESSION_ID`, which would otherwise stamp every session's rows\n * with the first session's id (`session.ts`). `NODE_OPTIONS` is deliberately\n * NOT kept: a `--require` from one shell would run inside a daemon that serves\n * every session on the machine. `TMP` rides with `TEMP` because `os.tmpdir()`\n * reads both on Windows.\n */\nexport function daemonEnv(\n dataDir: string,\n env: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const keep = [\n 'PATH',\n 'HOME',\n 'USERPROFILE',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'NO_PROXY',\n 'http_proxy',\n 'https_proxy',\n 'no_proxy',\n ];\n const out: NodeJS.ProcessEnv = {};\n for (const k of keep) if (env[k] !== undefined) out[k] = env[k];\n out.TENJIN_DATA_DIR = dataDir;\n return out;\n}\n\n/** Has a spawn within the backoff window failed to become healthy? */\nexport function inBackoff(dataDir: string, now: number = Date.now()): boolean {\n try {\n return now - statSync(daemonSpawnPath(dataDir)).mtimeMs < SPAWN_BACKOFF_MS;\n } catch {\n return false;\n }\n}\n\n/**\n * Spawn the bundle detached with stdout and stderr on `daemon.log`, and forget\n * it. The backoff file is touched first and removed only by a caller that saw\n * the daemon become healthy.\n */\nexport function spawnDaemon(dataDir: string, env: NodeJS.ProcessEnv = process.env): void {\n mkdirSync(dataDir, { recursive: true, mode: 0o700 });\n writeFileSync(daemonSpawnPath(dataDir), '');\n const log = openSync(daemonLogPath(dataDir), 'a');\n try {\n const child = spawn(process.execPath, [daemonBundlePath(dataDir)], {\n detached: true,\n stdio: ['ignore', log, log],\n env: daemonEnv(dataDir, env),\n // Never the hook's cwd: a detached daemon would pin a project worktree.\n cwd: dataDir,\n windowsHide: true,\n });\n child.unref();\n } finally {\n closeSync(log);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport type EnsureResult =\n { ok: true; health: Health; spawned: boolean } | { ok: false; reason: string };\n\n/**\n * Make sure a daemon for `dataDir` is healthy, spawning one if not (unless a\n * recent spawn never became healthy). Port from `daemon.pid`, never derived:\n * the daemon is the only one that knows what it bound.\n */\nexport async function ensureDaemon(\n dataDir: string,\n opts: { env?: NodeJS.ProcessEnv; spawnMs?: number; now?: () => number } = {},\n): Promise<EnsureResult> {\n const now = opts.now ?? (() => Date.now());\n const pid = readPid(dataDir);\n if (pid !== null) {\n const h = await health(pid.port);\n if (h !== null && h.data_dir === dataDir) return { ok: true, health: h, spawned: false };\n }\n if (!existsSync(daemonBundlePath(dataDir)))\n return { ok: false, reason: 'no bundle; run `tenjin daemon start`' };\n if (inBackoff(dataDir, now())) return { ok: false, reason: 'spawn backoff' };\n try {\n spawnDaemon(dataDir, opts.env);\n } catch (err) {\n return {\n ok: false,\n reason: `spawn failed: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const budget = opts.spawnMs ?? SPAWN_MS;\n const until = now() + budget;\n const settled = async (): Promise<Health | null> => {\n const fresh = readPid(dataDir);\n if (fresh === null || (pid !== null && fresh.started_at === pid.started_at)) return null;\n const h = await health(fresh.port);\n return h !== null && h.data_dir === dataDir ? h : null;\n };\n const won = (h: Health): EnsureResult => {\n try {\n unlinkSync(daemonSpawnPath(dataDir));\n } catch {\n // Already gone.\n }\n return { ok: true, health: h, spawned: true };\n };\n while (now() < until) {\n await sleep(20);\n const h = await settled();\n if (h !== null) return won(h);\n }\n // ONE PROBE PAST THE DEADLINE: the loop's last `sleep(20)` can land as the\n // clock passes `until` and skip the probe for a daemon that came up during\n // it. That boundary reported a healthy daemon as \"spawned but not healthy\n // within 500 ms\" (tenjin-agent#342), a verdict the operator then had to\n // disprove by hand. It costs one probe on a path about to fail anyway.\n const late = await settled();\n if (late !== null) return won(late);\n return { ok: false, reason: `spawned but not healthy within ${budget} ms` };\n}\n\n/**\n * `--harness <id>`: ensure, then forward stdin to `/hook/<id>` and write the\n * daemon's body to fd 1 (`writeFileSync`, never `process.stdout.write`: a pipe\n * write is asynchronous and an exit on the next line can truncate it).\n */\nexport async function forward(\n dataDir: string,\n harness: string,\n stdin: string,\n startedAt: number,\n): Promise<void> {\n const token = readToken(dataDir);\n if (token === null) {\n logDown(dataDir, 'no token; run `tenjin daemon start`');\n return;\n }\n const ensured = await ensureDaemon(dataDir);\n if (!ensured.ok) {\n logDown(dataDir, ensured.reason);\n return;\n }\n const remaining = HARNESS_MS - SLACK_MS - (Date.now() - startedAt);\n if (remaining <= 0) {\n logDown(dataDir, 'no time left after ensure');\n return;\n }\n try {\n const res = await fetch(`http://127.0.0.1:${ensured.health.port}/hook/${harness}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: stdin,\n signal: AbortSignal.timeout(remaining),\n });\n if (res.status === 200) {\n const body = await res.text();\n if (body.length > 0) writeFileSync(1, body);\n } else if (res.status === 404) {\n // The one status with a specific cause and a specific remedy: the daemon\n // answering is from a build with no route for this harness, so every\n // fire is dropped silently until it is replaced (tenjin-agent#342).\n logDown(\n dataDir,\n `hook answered 404: the daemon on 127.0.0.1:${ensured.health.port} (v${ensured.health.version}) has no /hook/${harness} route; run \\`tenjin install\\` to replace it`,\n );\n } else if (res.status !== 204) {\n logDown(dataDir, `hook answered ${res.status}`);\n }\n } catch (err) {\n logDown(dataDir, `forward failed: ${err instanceof Error ? err.name : String(err)}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,OAAO,OAAO,UAAU,UAAU,QAAAA,aAAY;AAC9D,SAAS,SAAS,QAAAC,aAAY;;;ACD9B,SAAS,gBAAgB;AACzB,SAAS,IAAI,YAAY;AACzB,SAAS,QAAAC,aAAY;;;ACFrB,SAAS,QAAAC,aAAY;;;AC+Ed,IAAM,iBAAiB,KAAK;AAwB5B,IAAM,cAAc;;;AC3EpB,IAAM,aAAa;AAOnB,IAAM,WAAW;AAIjB,IAAM,YAAY;AAQlB,IAAM,mBAAmB;AAwBzB,IAAM,iBAAiB,IAAI,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MAAM,MAAM,IAAI,MAAO,KAAK;AAC5D,WAAOF,MAAK,sBAAsB;AAAA,MAChC;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,SAAS,GAAG,IAAI;AAAA,MAChB,KAAKC,QAAO,oBAAoB;AAAA,IAClC,CAAC;AAAA,EACH;AACA,MAAI;AACF,UAAM,gBAAgB,MAAM,MAAM,EAAE,MAAM,IAAM,CAAC;AAAA,EACnD,SAAS,KAAK;AACZ,WAAOD,MAAK,cAAc;AAAA,MACxB;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,SAAS,GAAG,IAAI,0BAA0B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MAC1F,KAAKC,QAAO,YAAY;AAAA,IAC1B,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAGA,SAAS,UAAU,MAAyC;AAC1D,QAAM,UAAU,oBAAI,IAAuB;AAC3C,aAAW,QAAQ,MAAM;AACvB,QAAI,CAACE,eAAc,IAAI,KAAK,OAAO,KAAK,UAAU,SAAU;AAC5D,UAAM,EAAE,OAAO,GAAG,MAAM,IAAI;AAC5B,UAAM,OAAO,QAAQ,IAAI,KAAK,KAAK,CAAC;AACpC,SAAK,KAAK,KAAK;AACf,YAAQ,IAAI,OAAO,IAAI;AAAA,EACzB;AACA,SAAO;AACT;","names":["stat","join","join","join","resolve","isRecord","join","join","resolve","join","stat","stat","NATIVE_TO_EVENT","isRecord","str","canonicalTool","decode","encode","commandHandler","registrar","chmod","lstat","readFile","realpath","stat","existsSync","mkdirSync","writeFileSync","dirname","join","spawn","dataDir","dataDir","spawn","dirname","dataDir","mkdirSync","join","existsSync","writeFileSync","sleep","skip","fixFor","isPlainObject","dataDir","lstat","realpath","readFile","dataDir","isPlainObject","skip","fixFor","readFile","stat","chmod","skip","fixFor","readFile","isPlainObject"]}