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

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 (182) hide show
  1. package/README.md +51 -3
  2. package/dist/buy-VIRNSYGN.js +47 -0
  3. package/dist/{chunk-OC3EIDCP.js → chunk-2MYQN7HM.js} +71 -26
  4. package/dist/chunk-2MYQN7HM.js.map +1 -0
  5. package/dist/{chunk-XXY77EZJ.js → chunk-2RF2GIJQ.js} +57 -226
  6. package/dist/chunk-2RF2GIJQ.js.map +1 -0
  7. package/dist/chunk-3GL2Z5QK.js +57 -0
  8. package/dist/chunk-3GL2Z5QK.js.map +1 -0
  9. package/dist/{chunk-OXUJ3FXU.js → chunk-4CQIDQOT.js} +41 -8
  10. package/dist/chunk-4CQIDQOT.js.map +1 -0
  11. package/dist/{chunk-YMUJZWHB.js → chunk-4KG27W2S.js} +10 -10
  12. package/dist/chunk-4KG27W2S.js.map +1 -0
  13. package/dist/{chunk-SPUORKD7.js → chunk-5QQTYWEU.js} +13 -13
  14. package/dist/chunk-5QQTYWEU.js.map +1 -0
  15. package/dist/chunk-65DTCCJ7.js +21 -0
  16. package/dist/chunk-65DTCCJ7.js.map +1 -0
  17. package/dist/{chunk-BRAVLUGI.js → chunk-A5DKHMUN.js} +28 -13
  18. package/dist/chunk-A5DKHMUN.js.map +1 -0
  19. package/dist/chunk-B63XPWQ4.js +246 -0
  20. package/dist/chunk-B63XPWQ4.js.map +1 -0
  21. package/dist/{chunk-47YKYDOF.js → chunk-CAR6FHK6.js} +5 -5
  22. package/dist/{chunk-JVBMPU5G.js → chunk-CPCX67TI.js} +22 -22
  23. package/dist/{chunk-TXVC46SA.js → chunk-CQBVCYI2.js} +40 -53
  24. package/dist/chunk-CQBVCYI2.js.map +1 -0
  25. package/dist/chunk-DBU5CXBV.js +4731 -0
  26. package/dist/chunk-DBU5CXBV.js.map +1 -0
  27. package/dist/chunk-DHJD77OW.js +81 -0
  28. package/dist/chunk-DHJD77OW.js.map +1 -0
  29. package/dist/{chunk-XGZ5EVMB.js → chunk-EDZSNPE5.js} +2 -2
  30. package/dist/{chunk-736DW4V3.js → chunk-EFWZPUTC.js} +2 -2
  31. package/dist/chunk-EPFL6CTE.js +448 -0
  32. package/dist/chunk-EPFL6CTE.js.map +1 -0
  33. package/dist/{chunk-3P3ES4XU.js → chunk-GHLVXVZD.js} +3 -5
  34. package/dist/{chunk-3P3ES4XU.js.map → chunk-GHLVXVZD.js.map} +1 -1
  35. package/dist/{chunk-UUARTUY2.js → chunk-H3SOOJ2I.js} +264 -33
  36. package/dist/chunk-H3SOOJ2I.js.map +1 -0
  37. package/dist/{chunk-OUJDDY5L.js → chunk-HPJGOLTN.js} +32 -32
  38. package/dist/chunk-HPJGOLTN.js.map +1 -0
  39. package/dist/{chunk-J6FUAIRR.js → chunk-HRGBS2PA.js} +4 -6
  40. package/dist/{chunk-J6FUAIRR.js.map → chunk-HRGBS2PA.js.map} +1 -1
  41. package/dist/{chunk-NKN4YC5C.js → chunk-ITUXPJIS.js} +55 -58
  42. package/dist/chunk-ITUXPJIS.js.map +1 -0
  43. package/dist/{chunk-CA3JV7FX.js → chunk-JBIKAAT3.js} +2 -2
  44. package/dist/{chunk-CA3JV7FX.js.map → chunk-JBIKAAT3.js.map} +1 -1
  45. package/dist/{chunk-6JKD46OJ.js → chunk-KAJZHIQ4.js} +13 -10
  46. package/dist/chunk-KAJZHIQ4.js.map +1 -0
  47. package/dist/{chunk-OWVVI4VQ.js → chunk-KINZ23CV.js} +107 -4535
  48. package/dist/chunk-KINZ23CV.js.map +1 -0
  49. package/dist/{chunk-WMFRCSNC.js → chunk-LRYV3SK7.js} +9 -7
  50. package/dist/{chunk-WMFRCSNC.js.map → chunk-LRYV3SK7.js.map} +1 -1
  51. package/dist/{chunk-T4UWMVKV.js → chunk-NIKXHWOL.js} +11 -13
  52. package/dist/{chunk-T4UWMVKV.js.map → chunk-NIKXHWOL.js.map} +1 -1
  53. package/dist/chunk-OKDRDT74.js +209 -0
  54. package/dist/chunk-OKDRDT74.js.map +1 -0
  55. package/dist/chunk-OKYSNAS3.js +2144 -0
  56. package/dist/chunk-OKYSNAS3.js.map +1 -0
  57. package/dist/{chunk-B676GPS2.js → chunk-OLWTRUTS.js} +7 -3
  58. package/dist/{chunk-B676GPS2.js.map → chunk-OLWTRUTS.js.map} +1 -1
  59. package/dist/{chunk-WU5CZPLD.js → chunk-QQ6ELLSA.js} +6 -8
  60. package/dist/{chunk-WU5CZPLD.js.map → chunk-QQ6ELLSA.js.map} +1 -1
  61. package/dist/{chunk-WVHPGQH5.js → chunk-QZ6ROAJU.js} +8 -4
  62. package/dist/chunk-QZ6ROAJU.js.map +1 -0
  63. package/dist/{chunk-L4XNT3UW.js → chunk-R7RSCBI7.js} +167 -52
  64. package/dist/chunk-R7RSCBI7.js.map +1 -0
  65. package/dist/{chunk-ELVDOTU7.js → chunk-U6VPKMGC.js} +128 -28
  66. package/dist/chunk-U6VPKMGC.js.map +1 -0
  67. package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
  68. package/dist/chunk-UO22YNY4.js.map +1 -0
  69. package/dist/{chunk-IAR25V2E.js → chunk-US456VUI.js} +6 -6
  70. package/dist/{chunk-IKAJSA7E.js → chunk-V44J2MXV.js} +80 -34
  71. package/dist/chunk-V44J2MXV.js.map +1 -0
  72. package/dist/{chunk-IFPKA32J.js → chunk-VJQKL3YH.js} +10 -7
  73. package/dist/{chunk-IFPKA32J.js.map → chunk-VJQKL3YH.js.map} +1 -1
  74. package/dist/{chunk-GCGMXA2O.js → chunk-VJSQSLBM.js} +52 -20
  75. package/dist/chunk-VJSQSLBM.js.map +1 -0
  76. package/dist/{chunk-IGHSLJUF.js → chunk-VYOJOX4Z.js} +9 -7
  77. package/dist/chunk-VYOJOX4Z.js.map +1 -0
  78. package/dist/chunk-WY2K35OL.js +269 -0
  79. package/dist/chunk-WY2K35OL.js.map +1 -0
  80. package/dist/{chunk-PAOVPSP6.js → chunk-ZFJJ3EXC.js} +53 -5
  81. package/dist/chunk-ZFJJ3EXC.js.map +1 -0
  82. package/dist/chunk-ZOBNS7CX.js +73 -0
  83. package/dist/chunk-ZOBNS7CX.js.map +1 -0
  84. package/dist/{cli-XK5JZWU6.js → cli-KKRKBU5T.js} +76 -47
  85. package/dist/{cli-XK5JZWU6.js.map → cli-KKRKBU5T.js.map} +1 -1
  86. package/dist/config-JMRUNYE6.js +37 -0
  87. package/dist/discover-B5HF6SHM.js +102 -0
  88. package/dist/discover-B5HF6SHM.js.map +1 -0
  89. package/dist/doctor-ZBG7X66D.js +32 -0
  90. package/dist/edit-PZJIILQE.js +40 -0
  91. package/dist/{fund-JF6A76YS.js → fund-EUDH5KPA.js} +19 -17
  92. package/dist/index.js +1 -1
  93. package/dist/inspect-QC6WEQPN.js +37 -0
  94. package/dist/{install-YQVM3SUW.js → install-GNK2W3PI.js} +286 -447
  95. package/dist/install-GNK2W3PI.js.map +1 -0
  96. package/dist/outcome-KSGWZHUS.js +24 -0
  97. package/dist/pay-BC4UICPA.js +361 -0
  98. package/dist/pay-BC4UICPA.js.map +1 -0
  99. package/dist/publish-LXWFDIKF.js +42 -0
  100. package/dist/{read-UF7QVQOU.js → read-JMNUQ56P.js} +22 -20
  101. package/dist/{read-UF7QVQOU.js.map → read-JMNUQ56P.js.map} +1 -1
  102. package/dist/{run-GDZWHNWZ.js → run-XYTQ5TWQ.js} +54 -45
  103. package/dist/{run-GDZWHNWZ.js.map → run-XYTQ5TWQ.js.map} +1 -1
  104. package/dist/search-TSQAB45E.js +25 -0
  105. package/dist/{send-SI254H3R.js → send-G746D7PQ.js} +14 -14
  106. package/dist/{session-GJZJEXLJ.js → session-JBKWMJ24.js} +18 -17
  107. package/dist/{session-GJZJEXLJ.js.map → session-JBKWMJ24.js.map} +1 -1
  108. package/dist/{skill-heal-BPFT22XS.js → skill-heal-WKD67SLJ.js} +17 -9
  109. package/dist/skill-heal-WKD67SLJ.js.map +1 -0
  110. package/dist/skill-placement-RIU4AMC2.js +20 -0
  111. package/dist/{uninstall-7ZZG6WQ5.js → uninstall-5E263VTS.js} +15 -9
  112. package/dist/uninstall-5E263VTS.js.map +1 -0
  113. package/dist/{update-FPSBITLB.js → update-R76LHOZW.js} +18 -16
  114. package/dist/update-R76LHOZW.js.map +1 -0
  115. package/dist/{wallet-NS7TYWNN.js → wallet-TQ7D5EQ7.js} +7 -7
  116. package/dist/{wallet-TZVD2M4I.js → wallet-ZAVXWLWP.js} +11 -11
  117. package/dist/wallet-ZAVXWLWP.js.map +1 -0
  118. package/docs/agent-permissions.md +117 -18
  119. package/docs/command-reference.md +102 -50
  120. package/docs/safety-model.md +9 -0
  121. package/package.json +1 -1
  122. package/skills/tenjin/SKILL.md +38 -29
  123. package/skills/tenjin-pay/SKILL.md +76 -0
  124. package/skills/tenjin-publish/SKILL.md +184 -205
  125. package/skills/tenjin-publish/references/maintain.md +39 -0
  126. package/skills/tenjin-search/SKILL.md +92 -280
  127. package/skills/tenjin-search/references/permissions.md +112 -0
  128. package/dist/buy-X4VPHFUA.js +0 -44
  129. package/dist/chunk-3NZCU6SD.js +0 -125
  130. package/dist/chunk-3NZCU6SD.js.map +0 -1
  131. package/dist/chunk-6JKD46OJ.js.map +0 -1
  132. package/dist/chunk-BRAVLUGI.js.map +0 -1
  133. package/dist/chunk-ELVDOTU7.js.map +0 -1
  134. package/dist/chunk-FKSAUOJU.js.map +0 -1
  135. package/dist/chunk-GCGMXA2O.js.map +0 -1
  136. package/dist/chunk-IGHSLJUF.js.map +0 -1
  137. package/dist/chunk-IKAJSA7E.js.map +0 -1
  138. package/dist/chunk-L4XNT3UW.js.map +0 -1
  139. package/dist/chunk-NKN4YC5C.js.map +0 -1
  140. package/dist/chunk-OC3EIDCP.js.map +0 -1
  141. package/dist/chunk-OE36HRWG.js +0 -939
  142. package/dist/chunk-OE36HRWG.js.map +0 -1
  143. package/dist/chunk-OUJDDY5L.js.map +0 -1
  144. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  145. package/dist/chunk-OXUJ3FXU.js.map +0 -1
  146. package/dist/chunk-PAOVPSP6.js.map +0 -1
  147. package/dist/chunk-SPUORKD7.js.map +0 -1
  148. package/dist/chunk-TXVC46SA.js.map +0 -1
  149. package/dist/chunk-UUARTUY2.js.map +0 -1
  150. package/dist/chunk-WVHPGQH5.js.map +0 -1
  151. package/dist/chunk-XXY77EZJ.js.map +0 -1
  152. package/dist/chunk-YMUJZWHB.js.map +0 -1
  153. package/dist/chunk-ZQIQ55KK.js +0 -51
  154. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  155. package/dist/config-CNK7MYUR.js +0 -26
  156. package/dist/doctor-R7N7FUX5.js +0 -27
  157. package/dist/edit-QSUEG7CL.js +0 -38
  158. package/dist/inspect-NFNAA4LA.js +0 -35
  159. package/dist/install-YQVM3SUW.js.map +0 -1
  160. package/dist/outcome-IUSYFJTN.js +0 -22
  161. package/dist/publish-O2I6IAEL.js +0 -40
  162. package/dist/search-JVOHEF3E.js +0 -23
  163. package/dist/skill-heal-BPFT22XS.js.map +0 -1
  164. package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
  165. package/dist/update-FPSBITLB.js.map +0 -1
  166. /package/dist/{buy-X4VPHFUA.js.map → buy-VIRNSYGN.js.map} +0 -0
  167. /package/dist/{chunk-47YKYDOF.js.map → chunk-CAR6FHK6.js.map} +0 -0
  168. /package/dist/{chunk-JVBMPU5G.js.map → chunk-CPCX67TI.js.map} +0 -0
  169. /package/dist/{chunk-XGZ5EVMB.js.map → chunk-EDZSNPE5.js.map} +0 -0
  170. /package/dist/{chunk-736DW4V3.js.map → chunk-EFWZPUTC.js.map} +0 -0
  171. /package/dist/{chunk-IAR25V2E.js.map → chunk-US456VUI.js.map} +0 -0
  172. /package/dist/{config-CNK7MYUR.js.map → config-JMRUNYE6.js.map} +0 -0
  173. /package/dist/{doctor-R7N7FUX5.js.map → doctor-ZBG7X66D.js.map} +0 -0
  174. /package/dist/{edit-QSUEG7CL.js.map → edit-PZJIILQE.js.map} +0 -0
  175. /package/dist/{fund-JF6A76YS.js.map → fund-EUDH5KPA.js.map} +0 -0
  176. /package/dist/{inspect-NFNAA4LA.js.map → inspect-QC6WEQPN.js.map} +0 -0
  177. /package/dist/{outcome-IUSYFJTN.js.map → outcome-KSGWZHUS.js.map} +0 -0
  178. /package/dist/{publish-O2I6IAEL.js.map → publish-LXWFDIKF.js.map} +0 -0
  179. /package/dist/{search-JVOHEF3E.js.map → search-TSQAB45E.js.map} +0 -0
  180. /package/dist/{send-SI254H3R.js.map → send-G746D7PQ.js.map} +0 -0
  181. /package/dist/{wallet-NS7TYWNN.js.map → skill-placement-RIU4AMC2.js.map} +0 -0
  182. /package/dist/{wallet-TZVD2M4I.js.map → wallet-TQ7D5EQ7.js.map} +0 -0
@@ -20,7 +20,7 @@ var ALWAYS_SAFE_ALLOWLIST = [
20
20
  {
21
21
  rule: "Bash(tenjin read:*)",
22
22
  command: "tenjin read",
23
- note: "Free-only delivery: free pieces, local-library re-reads, and pieces this wallet already owns when a read-scoped session key is cached. Cannot spend and cannot open the keystore \u2014 the wallet, payment, and session-MINTING modules are all absent from its import graph, so the key it may present is a P-256 delegation loaded from disk, which is the wrong curve to authorize a payment. TRANSMITS A CREDENTIAL: when a session key exists, a cold 402 sends that wallet-derived delegation to the server. It goes only to the origin the delegation was minted for, which is what stops a stray `--base-url` from redirecting it, and no scope on it limits what a holder could do with it. Not read-only: a freshly delivered piece is saved to the library."
23
+ note: "Free-only delivery: free pieces, local-library re-reads, and pieces this wallet already owns when a read-scoped session key is cached. Cannot spend and cannot open the keystore: the wallet, payment, and session-MINTING modules are all absent from its import graph, so the key it may present is a P-256 delegation loaded from disk, which is the wrong curve to authorize a payment. TRANSMITS A CREDENTIAL: when a session key exists, a cold 402 sends that wallet-derived delegation to the server. It goes only to the origin the delegation was minted for, which is what stops a stray `--base-url` from redirecting it, and no scope on it limits what a holder could do with it. Not read-only: a freshly delivered piece is saved to the library."
24
24
  },
25
25
  {
26
26
  rule: "Bash(tenjin outcome:*)",
@@ -54,12 +54,32 @@ var OPT_IN_ALLOWLIST = [
54
54
  command: "tenjin buy",
55
55
  note: "SPENDS USDC on Base, unrefundably. This authorizes UNATTENDED purchases: `--yes` is an ordinary flag on the same allowlisted verb and it clears the confirm gate, so on the default config nothing stops a spend up to your wallet balance. Set a real ceiling first with `tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd>` (sessionBudget 0 means NO ceiling, not a zero one). This line never raises a spend cap by itself, but do not read that as a human being on every purchase. Fund small."
56
56
  },
57
+ {
58
+ rule: "Bash(tenjin pay:*)",
59
+ command: "tenjin pay",
60
+ note: "SPENDS USDC on Base, unrefundably, at ANY x402 endpoint the origin gate allows: the configured base URL always, and with `bazaarPay` on, registry-listed foreign sellers too. The same spend policy and `--yes` caveat as the buy line apply, and unlike `buy` there is no library dedupe: a looping agent pays on every call. Set maxAutoSpend and sessionBudget first, and leave `bazaarPay` off unless you mean it."
61
+ },
57
62
  {
58
63
  rule: "Bash(tenjin session start:*)",
59
64
  command: "tenjin session start",
60
- note: "OPENS THE KEYSTORE (one wallet signature), but SPENDS NOTHING and cannot: it mints a \u226424h P-256 session key so `tenjin read` can recover pieces you already own without paying. The delegated key is the wrong curve for a payment authorization, so no session file can ever move money. Do NOT read the `read` scope as a bound on the rest: the file it leaves is a wallet-derived credential, and what limits it is that it expires in 24h, lives 0600, and is refused off the origin it was minted for \u2014 not its scope. What you are opting into is unattended keystore access: on an encrypted wallet the passphrase prompt is skipped or answered from the environment, and the `--base-url` caveat below bites hardest here, because a mint against an attacker-chosen host is a wallet signature you did not intend to make."
65
+ note: "OPENS THE KEYSTORE (one wallet signature), but SPENDS NOTHING and cannot: it mints a \u226424h P-256 session key so `tenjin read` can recover pieces you already own without paying. The delegated key is the wrong curve for a payment authorization, so no session file can ever move money. Do NOT read the `read` scope as a bound on the rest: the file it leaves is a wallet-derived credential, and what limits it is that it expires in 24h, lives 0600, and is refused off the origin it was minted for, not its scope. What you are opting into is unattended keystore access: on an encrypted wallet the passphrase prompt is skipped or answered from the environment, and the `--base-url` caveat below bites hardest here, because a mint against an attacker-chosen host is a wallet signature you did not intend to make."
61
66
  }
62
67
  ];
68
+ var PUBLISH_MODE_ALLOWLIST = [
69
+ {
70
+ rule: "Bash(tenjin publish:*)",
71
+ command: "tenjin publish",
72
+ note: "PUBLISHES PUBLICLY under your identity, and is cleared only while publish.mode is auto or full-auto: the mode is the consent, and the harness prompt would ask for it twice. Three things it clears that the free tier never did. It OPENS THE KEYSTORE: publish always resolves a signer, and with no usable session it mints one at read+write scope, which is strictly broader than the read-only key `tenjin session start` exists as a deliberate opt-in for. It publishes the contents of ANY LOCAL FILE the agent can read, gated only by the heuristic scan. And it is a PREFIX rule, so it pins the verb and not the flags: `--base-url` rides it (see the flag caveat), and `--yes` is an ordinary flag on the same verb that clears exactly the WARN findings auto stopped on, so a re-run collapses auto into full-auto with nobody asked. What still gates a publish is the CLI: the deterministic secret scan blocks in every mode and no --yes clears it. The skills hold the rest of that line. Set publish.mode back to review and the rule is retracted."
73
+ },
74
+ {
75
+ rule: "Bash(tenjin edit:*)",
76
+ command: "tenjin edit",
77
+ note: "Updates posts your wallet ALREADY OWNS: reprices, refreshes an as-of date, repairs an answer card. Owner-scoped on both legs (GET and PUT /api/posts/<id> are signed and owner-only), spends nothing, moves no keys, and creates no new public content: a narrower blast radius than the publish rule beside it. It rides the same mode for the same reason: edit runs the identical publish.mode consent gate in the CLI (lib/consent.ts needsConfirmation), so a mode that publishes unattended and then cannot fix its own post\u2019s price is the asymmetry the mode exists to remove. It opens the keystore on the same terms as the publish rule beside it, and takes the same prefix-rule caveats. Removed by the same return to review."
78
+ }
79
+ ];
80
+ function modeGatedAllowlist(mode) {
81
+ return mode === "review" ? [] : PUBLISH_MODE_ALLOWLIST.map((e) => ({ ...e }));
82
+ }
63
83
  var NEVER_ALLOWLISTED = [
64
84
  {
65
85
  command: "tenjin send",
@@ -67,11 +87,11 @@ var NEVER_ALLOWLISTED = [
67
87
  },
68
88
  {
69
89
  command: "tenjin publish",
70
- reason: "Puts your content on a public marketplace under your identity."
90
+ reason: "Puts your content on a public marketplace under your identity. Never pre-cleared by the free tier or an opt-in line: the only thing that clears it is `publish.mode` auto or full-auto, which is the same human decision said once instead of twice (see PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again."
71
91
  },
72
92
  {
73
93
  command: "tenjin edit",
74
- reason: "Write-capable despite the no-flag form reading as a pure show: it edits live posts and answer cards under your identity, and moves prices. A prefix rule pins the verb, not the flags, so no rule can clear the read half without clearing the write half."
94
+ reason: "Write-capable despite the no-flag form reading as a pure show: it edits live posts and answer cards under your identity, and moves prices. A prefix rule pins the verb, not the flags, so no rule can clear the read half without clearing the write half. Never pre-cleared as a recommendation: like `tenjin publish`, the only thing that clears it is `publish.mode` auto or full-auto, whose consent gate it already shares (see PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again."
75
95
  },
76
96
  {
77
97
  command: "tenjin wallet create",
@@ -104,20 +124,28 @@ var FLAG_CAVEAT = [
104
124
  "Allowlist these verbs only if you are content for the agent to choose the destination",
105
125
  "host, and set the base URL in config instead of letting it be an argument. The skills",
106
126
  "tell agents never to pass --base-url on an allowlisted verb, but that is a convention,",
107
- "not an enforced boundary."
127
+ "not an enforced boundary.",
128
+ "This covers the two rules your publish.mode carries as well, and bites hardest there:",
129
+ "`tenjin publish --base-url <host>` is cleared by default on auto, and it signs against",
130
+ "the host it is given."
108
131
  ];
109
132
  var MCP_CAVEAT = [
133
+ "Note the asymmetry: publish.mode writes the Bash rules for `publish` and `edit`, and",
134
+ "deliberately does not touch the MCP tool grants below. The mode is a CLI-side consent",
135
+ "gate, and nothing reads it on the MCP surface, so clearing those tools would hand out",
136
+ "the same authority with none of the same gate. Aligning the two is tracked separately.",
110
137
  "Running the local MCP server (`tenjin mcp`) instead? That is a different permission",
111
138
  "surface: the harness gates TOOLS there, and these Bash rules do not apply. Leave",
112
139
  "`mcp__tenjin__tenjin_publish`, `mcp__tenjin__tenjin_edit`, and",
113
140
  "`mcp__tenjin__tenjin_wallet` gated. `tenjin_buy` is the same opt-in decision as the",
114
141
  "buy line above."
115
142
  ];
116
- function recommendedPermissions() {
143
+ function recommendedPermissions(mode = "review") {
117
144
  return {
118
145
  alwaysSafe: ALWAYS_SAFE_ALLOWLIST.map((e) => ({ ...e })),
119
146
  optIn: OPT_IN_ALLOWLIST.map((e) => ({ ...e })),
120
147
  neverAllowlisted: NEVER_ALLOWLISTED.map((e) => ({ ...e })),
148
+ modeGated: modeGatedAllowlist(mode),
121
149
  caveats: { flags: [...FLAG_CAVEAT], mcp: [...MCP_CAVEAT] }
122
150
  };
123
151
  }
@@ -125,10 +153,15 @@ var PERMISSIONS_DOC_URL = "https://github.com/BackTrackCo/tenjin-agent/blob/main
125
153
  function permissionsPointer() {
126
154
  return `Auto-mode permission allowlist and subagent delegation (${ALWAYS_SAFE_ALLOWLIST.length} free verbs, ${OPT_IN_ALLOWLIST.length} opt-ins, the --base-url caveat): ${PERMISSIONS_DOC_URL}`;
127
155
  }
156
+ function modeGatedPointer(mode, missing, remedy = "tenjin install") {
157
+ if (modeGatedAllowlist(mode).length === 0 || missing.length === 0) return null;
158
+ return `publish.mode=${mode} also needs ${missing.join(" and ")} in your harness allowlist, or it will prompt anyway; \`${remedy}\` writes them.`;
159
+ }
128
160
 
129
161
  export {
130
162
  recommendedPermissions,
131
163
  PERMISSIONS_DOC_URL,
132
- permissionsPointer
164
+ permissionsPointer,
165
+ modeGatedPointer
133
166
  };
134
- //# sourceMappingURL=chunk-OXUJ3FXU.js.map
167
+ //# sourceMappingURL=chunk-4CQIDQOT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/permissions.ts"],"sourcesContent":["/**\n * The recommended HARNESS permission allowlist: the exact rule lines an operator\n * pastes into Claude Code (or an equivalent harness) so auto mode stops denying\n * the free Tenjin verbs, and so the one paying verb is cleared deliberately\n * rather than by accident.\n *\n * This is a HARNESS-side allowlist (which shell commands the agent may run at\n * all). It is NOT the CLI's spend policy and shares nothing with it: the shipped\n * `allowlistCreators` config key gates WHO you may pay, this file gates WHICH\n * COMMANDS the harness will run without a prompt. The two are deliberately kept\n * apart in name and in code — clearing `Bash(tenjin buy:*)` here never raises a\n * spend cap. That is a claim about this file, NOT a claim that the spend policy\n * stops an allowlisted `buy`: `--yes` is an ordinary flag on an allowlisted verb\n * and `confirmSpend` returns true on it before any TTY check\n * (src/commands/buy.ts), so under CONFIG_DEFAULTS nothing denies. See\n * OPT_IN_ALLOWLIST's note for the walk-through.\n *\n * These are static, shipped constants on purpose: there is NO config key for\n * them. An operator-editable \"which commands may run\" list stored next to the\n * spend policy would be a second, weaker copy of a control the harness already\n * owns, and a CLI that could widen its own permission grant is exactly the shape\n * this file exists to avoid.\n *\n * Scope: `tenjin mcp` exposes the same command cores over MCP, where the harness\n * gates TOOLS, not Bash lines. These rules say nothing about that surface, which\n * is why `tenjin mcp` is itself never recommended here: clearing it would route\n * around every rule below. MCP_CAVEAT names the tools to leave gated for an\n * operator who runs the server anyway.\n *\n * LIMIT OF A PREFIX RULE, read this before adding an entry: the rule constrains\n * the VERB and nothing else. `addGlobalFlags` (src/cli.ts) puts `--json`,\n * `--timeout`, and `--base-url` on every leaf command, so every rule below also\n * clears `--base-url <url>` in trailing position. `--base-url` is validated as a\n * URL and nothing more, and it wins settings precedence, so it re-points the\n * trust boundary itself: the `search` question goes to that host, `doctor` probes\n * it, and `assertOnBaseOrigin` only checks that a resource URL shares an origin\n * with the CONFIGURED base, so an attacker-controlled pair satisfies the pin. No\n * prefix syntax expresses \"this verb but not that flag\", so the mitigation is\n * disclosure rather than a narrower rule: FLAG_CAVEAT rides the `--json` payload\n * and docs/agent-permissions.md, every human surface points at that page, and the\n * skills tell the agent never to pass `--base-url` on an allowlisted verb. Pinning\n * the paying path to a constant origin instead is the real fix and is an\n * x402/payments-semantics change, tracked separately.\n */\n\nimport type { PublishMode } from './config';\n\n/** One pasteable allowlist rule plus why it is safe (or what it costs). */\nexport interface AllowlistEntry {\n /** The exact line to add to the harness permission allowlist. */\n rule: string;\n /** The verb it clears. */\n command: string;\n /** Why it is safe to pre-clear, or what the operator is opting into. */\n note: string;\n}\n\n/** A verb deliberately kept OUT of the recommended allowlist, and why. */\nexport interface ExcludedVerb {\n command: string;\n reason: string;\n}\n\n/**\n * FREE verbs: they CANNOT SPEND AND CANNOT MOVE YOUR KEYS. That is the whole\n * definition of this tier, and it is deliberately narrower than the older \"no\n * wallet, no signing, no payment\" — which stopped being true the moment `read`\n * gained the ability to PRESENT a cached session key. `read` signs, with a P-256\n * delegation loaded from disk; it cannot mint one (that needs the wallet, and its\n * import graph is test-pinned clear of it) and cannot produce the\n * secp256k1/EIP-712 signature a payment authorization needs (wrong curve). Money\n * stays out of reach; a signature as such no longer does, so the tier says what\n * it means. `doctor` decrypts locally to check the wallet still opens.\n *\n * What the tier does NOT claim, because it is not true: that the read scope\n * limits what a leaked delegation is worth. Scope is enforced only on the request\n * shape that carries both a session signature and the delegation header; the same\n * delegation replayed as a plain `SIGN-IN-WITH-X` takes a different server path\n * where no scope logic runs. So a session file is a wallet-derived credential\n * with the authority of the wallet behind it, and the mitigations that actually\n * hold are the ones in this repo: it is 0600, short-lived (≤24h, server-clamped),\n * bound to the origin it was minted for, and never presented off that origin.\n * Treat \"read is allowlisted\" as \"read may transmit that credential to the\n * configured origin\", and see FLAG_CAVEAT for why the configured origin is not\n * automatically the one you configured.\n *\n * Not all of them are read-only, and the difference is disclosed rather than\n * papered over — `search` POSTs the (generalized, anonymous) question off-machine\n * and records it locally, `outcome` POSTs a report that moves the marketplace's\n * reuse signal (both unauthenticated remote writes), and `read` writes locally,\n * saving a delivered piece to the library, and `doctor` decrypts the keystore\n * locally to check it opens. Pre-clearing them is defensible because they cost\n * nothing and none of it leaves the machine; calling them read-only to justify it\n * would not be.\n *\n * Rules are PREFIX rules: `Bash(tenjin search:*)` clears commands that start with\n * `tenjin search` and nothing else. The narrow `wallet show` / `wallet balance` /\n * The `config get` form is deliberate: a `Bash(tenjin wallet:*)`\n * or `Bash(tenjin config:*)` rule would silently swallow `wallet create` and\n * `config set`, and `config set` can raise the spend caps.\n *\n * Two known gaps, both fail-closed (denied, never wrongly allowed):\n * - Bare `tenjin config` (runConfigList) is as read-only as `config get`, but no\n * prefix rule reaches it without also covering `config set`, so it stays out.\n * Use `tenjin config get <key>`, which is a different supported command rather\n * than a reworded one.\n * - Group-level flag forms like `tenjin wallet --json show` are not covered.\n * Put global flags AFTER the leaf verb (`tenjin wallet show --json`); the\n * CLI parses either, and only the trailing form matches these rules.\n */\nexport const ALWAYS_SAFE_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin search:*)',\n command: 'tenjin search',\n note:\n 'Free anonymous marketplace search. No wallet, no signing, no payment. ' +\n 'Not read-only: it POSTs the generalized question off-machine and records ' +\n 'the search locally.',\n },\n {\n rule: 'Bash(tenjin fund:*)',\n command: 'tenjin fund',\n note:\n 'Owner call (2026-08-12): free on both surfaces, because the command just opens the ' +\n 'fund modal. Minting moves no money: the destination is server-pinned to the wallet ' +\n 'that signed, the CLI refuses any checkout host but pay.coinbase.com, and payment ' +\n 'happens behind Coinbase\\u2019s own human gate. The usual --base-url caveat does not ' +\n 'apply: fund is pinned to the production origin and takes no override from flag, ' +\n 'env, or config.',\n },\n {\n rule: 'Bash(tenjin inspect:*)',\n command: 'tenjin inspect',\n note: 'Free pre-purchase card and preview. Never signs, never pays, never saves.',\n },\n {\n rule: 'Bash(tenjin read:*)',\n command: 'tenjin read',\n note:\n 'Free-only delivery: free pieces, local-library re-reads, and pieces this ' +\n 'wallet already owns when a read-scoped session key is cached. Cannot spend ' +\n 'and cannot open the keystore: the wallet, payment, and session-MINTING ' +\n 'modules are all absent from its import graph, so the key it may present is ' +\n 'a P-256 delegation loaded from disk, which is the wrong curve to authorize ' +\n 'a payment. TRANSMITS A CREDENTIAL: when a session key exists, a cold 402 ' +\n 'sends that wallet-derived delegation to the server. It goes only to the ' +\n 'origin the delegation was minted for, which is what stops a stray ' +\n '`--base-url` from redirecting it, and no scope on it limits what a holder ' +\n 'could do with it. Not read-only: a freshly delivered piece is saved to the ' +\n 'library.',\n },\n {\n rule: 'Bash(tenjin outcome:*)',\n command: 'tenjin outcome',\n note:\n 'Free honest outcome report on a past search. No wallet, no payment. ' +\n 'Not read-only: it POSTs a report that moves the marketplace reuse signal.',\n },\n {\n rule: 'Bash(tenjin doctor:*)',\n command: 'tenjin doctor',\n note:\n 'Local environment and API reachability diagnostics. Decrypts the wallet ' +\n 'locally to check it still opens; signs nothing and sends nothing.',\n },\n {\n rule: 'Bash(tenjin wallet show:*)',\n command: 'tenjin wallet show',\n note: 'Prints the wallet address and key source. Never prints the key.',\n },\n {\n rule: 'Bash(tenjin wallet balance:*)',\n command: 'tenjin wallet balance',\n note: 'Read-only USDC balance query on Base.',\n },\n {\n rule: 'Bash(tenjin config get:*)',\n command: 'tenjin config get',\n note:\n 'Reads one effective config value. `config set` is excluded on purpose. ' +\n 'Note `config get rpcUrl` returns your RPC URL, which commonly embeds a ' +\n 'provider API key: no wallet secret, but a credential-adjacent read.',\n },\n];\n\n/**\n * The verbs offered as EXPLICIT opt-in lines rather than shipped in the safe set:\n * the one that spends, and the one that opens the keystore.\n *\n * Read the buy note carefully before pasting the line: on the DEFAULT config this\n * rule authorizes unattended spending up to the wallet balance. Walking\n * evaluateSpendPolicy (lib/policy.ts) against CONFIG_DEFAULTS with an agent that\n * passes `--yes` (which this repo's own skill snippet offers):\n * - `maxPriceAtomic` is unset unless the agent chooses to pass `--max-price`;\n * - `allowlistCreators` is empty, so the creator gate is off;\n * - `sessionBudget` is '0', which `if (policy.sessionBudgetAtomic > 0n)` reads\n * as DISABLED, not as a zero ceiling;\n * - `maxAutoSpend` '0' and `confirm` 'always' both land on `confirm`, and\n * `confirmSpend` returns true on `--yes` before any TTY check.\n * Nothing denies. Note the asymmetry that makes the pair read safer than it is:\n * `maxAutoSpend: '0'` means \"auto-approve nothing\" while `sessionBudget: '0'`\n * means \"no ceiling at all\".\n */\nexport const OPT_IN_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin buy:*)',\n command: 'tenjin buy',\n note:\n 'SPENDS USDC on Base, unrefundably. This authorizes UNATTENDED purchases: ' +\n '`--yes` is an ordinary flag on the same allowlisted verb and it clears the ' +\n 'confirm gate, so on the default config nothing stops a spend up to your ' +\n 'wallet balance. Set a real ceiling first with ' +\n '`tenjin config set maxAutoSpend <usd>` and ' +\n '`tenjin config set sessionBudget <usd>` (sessionBudget 0 means NO ceiling, ' +\n 'not a zero one). This line never raises a spend cap by itself, but do not ' +\n 'read that as a human being on every purchase. Fund small.',\n },\n {\n rule: 'Bash(tenjin pay:*)',\n command: 'tenjin pay',\n note:\n 'SPENDS USDC on Base, unrefundably, at ANY x402 endpoint the origin gate ' +\n 'allows: the configured base URL always, and with `bazaarPay` on, ' +\n 'registry-listed foreign sellers too. The same spend policy and `--yes` ' +\n 'caveat as the buy line apply, and unlike `buy` there is no library ' +\n 'dedupe: a looping agent pays on every call. Set maxAutoSpend and ' +\n 'sessionBudget first, and leave `bazaarPay` off unless you mean it.',\n },\n {\n rule: 'Bash(tenjin session start:*)',\n command: 'tenjin session start',\n note:\n 'OPENS THE KEYSTORE (one wallet signature), but SPENDS NOTHING and cannot: ' +\n 'it mints a ≤24h P-256 session key so `tenjin read` can recover pieces you ' +\n 'already own without paying. The delegated key is the wrong curve for a ' +\n 'payment authorization, so no session file can ever move money. Do NOT read ' +\n 'the `read` scope as a bound on the rest: the file it leaves is a ' +\n 'wallet-derived credential, and what limits it is that it expires in 24h, ' +\n 'lives 0600, and is refused off the origin it was minted for, not its ' +\n 'scope. What you are opting into is unattended keystore access: on an ' +\n 'encrypted wallet the passphrase prompt is skipped or answered from the ' +\n 'environment, and the `--base-url` caveat below bites hardest here, because ' +\n 'a mint against an attacker-chosen host is a wallet signature you did not ' +\n 'intend to make.',\n },\n];\n\n/**\n * The one rule that is neither always-safe nor a standing opt-in: it exists only\n * while `publish.mode` is `auto` or `full-auto`.\n *\n * The mode IS the consent. An operator who set auto has already said a clean\n * publish should proceed without asking; leaving the harness prompt in front of\n * it asks the same question a second time, in a place the mode cannot answer,\n * and the agent that hits it does the only safe thing and stops. That was the\n * observed failure: a session ran `tenjin config get publish.mode` mid-publish to\n * discover it had permission it had already been given (#161).\n *\n * NOT part of {@link recommendedRules}, and not a tier an operator picks from.\n * There is no line to paste and no flag that adds it: `install` writes it when\n * the mode it just settled is auto or full-auto, takes it back when the mode is\n * review, and `uninstall` reclaims it like every other rule this CLI wrote.\n */\nexport const PUBLISH_MODE_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin publish:*)',\n command: 'tenjin publish',\n note:\n 'PUBLISHES PUBLICLY under your identity, and is cleared only while publish.mode is ' +\n 'auto or full-auto: the mode is the consent, and the harness prompt would ask for it ' +\n 'twice. Three things it clears that the free tier never did. It OPENS THE KEYSTORE: ' +\n 'publish always resolves a signer, and with no usable session it mints one at ' +\n 'read+write scope, which is strictly broader than the read-only key ' +\n '`tenjin session start` exists as a deliberate opt-in for. It publishes the contents ' +\n 'of ANY LOCAL FILE the agent can read, gated only by the heuristic scan. And it is a ' +\n 'PREFIX rule, so it pins the verb and not the flags: `--base-url` rides it (see the ' +\n 'flag caveat), and `--yes` is an ordinary flag on the same verb that clears exactly ' +\n 'the WARN findings auto stopped on, so a re-run collapses auto into full-auto with ' +\n 'nobody asked. What still gates a publish is the CLI: the deterministic secret scan ' +\n 'blocks in every mode and no --yes clears it. The skills hold the rest of that line. ' +\n 'Set publish.mode back to review and the rule is retracted.',\n },\n {\n rule: 'Bash(tenjin edit:*)',\n command: 'tenjin edit',\n note:\n 'Updates posts your wallet ALREADY OWNS: reprices, refreshes an as-of date, repairs an ' +\n 'answer card. Owner-scoped on both legs (GET and PUT /api/posts/<id> are signed and ' +\n 'owner-only), spends nothing, moves no keys, and creates no new public content: a ' +\n 'narrower blast radius than the publish rule beside it. It rides the same mode for the ' +\n 'same reason: edit runs the identical publish.mode consent gate in the CLI ' +\n '(lib/consent.ts needsConfirmation), so a mode that publishes unattended and then ' +\n 'cannot fix its own post\\u2019s price is the asymmetry the mode exists to remove. It ' +\n 'opens the keystore on the same terms as the publish rule beside it, and takes the ' +\n 'same prefix-rule caveats. Removed by the same return to review.',\n },\n];\n\n/** The mode-gated rules in effect for `mode`; empty on review. */\nexport function modeGatedAllowlist(mode: PublishMode): AllowlistEntry[] {\n return mode === 'review' ? [] : PUBLISH_MODE_ALLOWLIST.map((e) => ({ ...e }));\n}\n\n/**\n * Verbs that must NEVER appear in the recommended allowlist, with the reason each\n * one is a human decision. `tenjin send` is the wallet escape hatch (tenjin-agent\n * #40) and heads this list: it moves USDC to an arbitrary address, outside the\n * spend policy that bounds `buy`. Naming it here is load-bearing even in versions\n * where the verb does not exist yet — the exclusion ships before the verb does.\n *\n * `tenjin publish` stays on this list under its own terms: nothing RECOMMENDS it,\n * and no line here or on the doc page adds it. {@link PUBLISH_MODE_ALLOWLIST} is\n * not a recommendation — it is what one specific operator choice already means.\n */\nexport const NEVER_ALLOWLISTED: readonly ExcludedVerb[] = [\n {\n command: 'tenjin send',\n reason:\n 'Moves USDC out of the wallet to an arbitrary address (the escape hatch, #40). ' +\n 'Irreversible and not bounded by the buy spend policy. Always a human decision.',\n },\n {\n command: 'tenjin publish',\n reason:\n 'Puts your content on a public marketplace under your identity. Never pre-cleared by the ' +\n 'free tier or an opt-in line: the only thing that clears it is `publish.mode` auto or ' +\n 'full-auto, which is the same human decision said once instead of twice (see ' +\n 'PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again.',\n },\n {\n command: 'tenjin edit',\n reason:\n 'Write-capable despite the no-flag form reading as a pure show: it edits live posts ' +\n 'and answer cards under your identity, and moves prices. A prefix rule pins the verb, ' +\n 'not the flags, so no rule can clear the read half without clearing the write half. ' +\n 'Never pre-cleared as a recommendation: like `tenjin publish`, the only thing that ' +\n 'clears it is `publish.mode` auto or full-auto, whose consent gate it already shares ' +\n '(see PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again.',\n },\n {\n command: 'tenjin wallet create',\n reason: 'Creates the payment credential; a stray run is a wallet you did not mean to have.',\n },\n {\n command: 'tenjin config set',\n reason:\n 'Can raise maxAutoSpend / sessionBudget / confirm, i.e. widen the agent’s own spend policy.',\n },\n {\n command: 'tenjin install',\n reason: 'Writes into harness config and skills directories.',\n },\n {\n command: 'tenjin mcp',\n reason:\n 'Long-running server that re-exposes every command core over stdio; ' +\n 'clearing it would indirectly clear everything above.',\n },\n {\n command: 'tenjin update',\n reason:\n 'Replaces the tenjin binary the agent then runs, with whatever npm serves ' +\n 'next. Which build an agent executes is an operator decision, not something ' +\n 'a rule pre-clears. `--check` only reports, but a prefix rule pins the verb, ' +\n 'not the flags.',\n },\n];\n\n/**\n * The flag-surface caveat. A prefix rule pins the verb, never the flags, and the\n * flag that matters is `--base-url`: it is accepted on every leaf, validated only\n * as a URL, and it wins settings precedence, so it moves the destination of every\n * allowlisted verb. Printed with the rules everywhere they are printed, because\n * an operator who only reads the verb list would never learn it.\n */\nexport const FLAG_CAVEAT: readonly string[] = [\n 'Caveat: a prefix rule pins the VERB, not the flags. Every line above also clears',\n '`--base-url <url>` on that verb, which re-points where the question, the probe, the',\n 'session key `read` may present, and (for buy) the signature and payment go. Signed',\n 'and credential-bearing traffic is NOT confined to the paying verb: `read` is in the',\n 'safe tier and still transmits a wallet-derived delegation once one is cached, which is',\n 'why that delegation is bound to the origin it was minted for and refused elsewhere.',\n 'Allowlist these verbs only if you are content for the agent to choose the destination',\n 'host, and set the base URL in config instead of letting it be an argument. The skills',\n 'tell agents never to pass --base-url on an allowlisted verb, but that is a convention,',\n 'not an enforced boundary.',\n 'This covers the two rules your publish.mode carries as well, and bites hardest there:',\n '`tenjin publish --base-url <host>` is cleared by default on auto, and it signs against',\n 'the host it is given.',\n];\n\n/**\n * The MCP caveat. `tenjin mcp` is never recommended as a Bash rule, but an\n * operator who registers the server anyway is on a different permission surface\n * (tools, not command strings) where three excluded verbs come back.\n */\nexport const MCP_CAVEAT: readonly string[] = [\n 'Note the asymmetry: publish.mode writes the Bash rules for `publish` and `edit`, and',\n 'deliberately does not touch the MCP tool grants below. The mode is a CLI-side consent',\n 'gate, and nothing reads it on the MCP surface, so clearing those tools would hand out',\n 'the same authority with none of the same gate. Aligning the two is tracked separately.',\n 'Running the local MCP server (`tenjin mcp`) instead? That is a different permission',\n 'surface: the harness gates TOOLS there, and these Bash rules do not apply. Leave',\n '`mcp__tenjin__tenjin_publish`, `mcp__tenjin__tenjin_edit`, and',\n '`mcp__tenjin__tenjin_wallet` gated. `tenjin_buy` is the same opt-in decision as the',\n 'buy line above.',\n];\n\n/** The machine shape emitted by `tenjin doctor --json` and `tenjin install --json`. */\nexport interface RecommendedPermissions {\n alwaysSafe: AllowlistEntry[];\n optIn: AllowlistEntry[];\n neverAllowlisted: ExcludedVerb[];\n /**\n * Rules the CURRENT publish.mode carries, empty on review. Separate from the\n * three tiers above because it is not a recommendation to weigh: it is what\n * this machine's mode already means, so a consumer that renders it beside the\n * others would be offering a choice that has been made.\n */\n modeGated: AllowlistEntry[];\n /** Caveats that qualify the rules above; never omit them when rendering. */\n caveats: { flags: string[]; mcp: string[] };\n}\n\n/** `mode` defaults to the shipped `review`, i.e. no mode-gated rules. */\nexport function recommendedPermissions(mode: PublishMode = 'review'): RecommendedPermissions {\n return {\n alwaysSafe: ALWAYS_SAFE_ALLOWLIST.map((e) => ({ ...e })),\n optIn: OPT_IN_ALLOWLIST.map((e) => ({ ...e })),\n neverAllowlisted: NEVER_ALLOWLISTED.map((e) => ({ ...e })),\n modeGated: modeGatedAllowlist(mode),\n caveats: { flags: [...FLAG_CAVEAT], mcp: [...MCP_CAVEAT] },\n };\n}\n\n/** Every rule this module recommends adding (safe + opt-in). */\nexport function recommendedRules(): string[] {\n return [...ALWAYS_SAFE_ALLOWLIST, ...OPT_IN_ALLOWLIST].map((e) => e.rule);\n}\n\n/**\n * The permission caveats' one home. `doctor` used to print the whole thing —\n * nine rules, both opt-in notes, every exclusion, the flag caveat and the MCP\n * caveat, ~60 lines ahead of the check list it was actually run for. No doctor\n * command in the wider ecosystem carries security prose, and an operator reading\n * a wall of it in a terminal cannot paste from it, search it, or link a colleague\n * to a section. The page can do all three, so it is where the caveats live and\n * where every human surface points; `--json` still carries them as data\n * (`recommendedPermissions`), which is what an agent reads.\n */\nexport const PERMISSIONS_DOC_URL =\n 'https://github.com/BackTrackCo/tenjin-agent/blob/main/docs/agent-permissions.md';\n\n/**\n * The single line that replaced the block: what is on the page, and its URL. It\n * names the counts rather than the rules so the operator knows whether the page\n * answers their question before they open it.\n *\n * Subagent delegation is named here rather than on a second line, because doctor\n * deliberately closes with ONE pointer (#81) and the operator deciding what to\n * hand a subagent is reading exactly this line. The free tier IS the\n * subagent-safe set, so the counts already answer the question; which verbs stay\n * human-gated lives on the page with every other caveat.\n */\nexport function permissionsPointer(): string {\n return (\n `Auto-mode permission allowlist and subagent delegation (${ALWAYS_SAFE_ALLOWLIST.length} free verbs, ` +\n `${OPT_IN_ALLOWLIST.length} opt-ins, the --base-url caveat): ${PERMISSIONS_DOC_URL}`\n );\n}\n\n/**\n * The rules the current mode is missing, or null when it needs none. This one\n * DOES name them,\n * unlike {@link permissionsPointer}: they are not a tier to weigh and paste, they\n * are lines that should already be in the operator's settings file, and an\n * operator whose agent is being prompted for work the mode said not to ask about\n * needs to see exactly which rules are missing.\n *\n * CONSULTS THE MACHINE. Rendering from the mode alone told operators to add\n * rules their settings file already had, and named a remedy that in one case\n * would not have written anything — a nag that is wrong twice over on a line\n * whose whole job is to prevent an agent stalling on a prompt (#161).\n */\nexport function modeGatedPointer(\n mode: PublishMode,\n /** The mode-gated rules this machine is actually MISSING. Empty renders nothing. */\n missing: readonly string[],\n /**\n * The command that would fix it. `tenjin install` for the ordinary case; a\n * mode coming from TENJIN_PUBLISH_MODE needs `config set` instead, because\n * install resolves the mode from the global file and would write nothing.\n */\n remedy = 'tenjin install',\n): string | null {\n if (modeGatedAllowlist(mode).length === 0 || missing.length === 0) return null;\n return `publish.mode=${mode} also needs ${missing.join(' and ')} in your harness allowlist, or it will prompt anyway; \\`${remedy}\\` writes them.`;\n}\n"],"mappings":";;;AA8GO,IAAM,wBAAmD;AAAA,EAC9D;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAGJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAMJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAWJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAEJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAEJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAGJ;AACF;AAoBO,IAAM,mBAA8C;AAAA,EACzD;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAQJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAMJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAYJ;AACF;AAkBO,IAAM,yBAAoD;AAAA,EAC/D;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA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AG,EAAE,EAAE;AAAA,IACzD,WAAW,mBAAmB,IAAI;AAAA,IAClC,SAAS,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG,KAAK,CAAC,GAAG,UAAU,EAAE;AAAA,EAC3D;AACF;AAiBO,IAAM,sBACX;AAaK,SAAS,qBAA6B;AAC3C,SACE,2DAA2D,sBAAsB,MAAM,gBACpF,iBAAiB,MAAM,qCAAqC,mBAAmB;AAEtF;AAeO,SAAS,iBACd,MAEA,SAMA,SAAS,kBACM;AACf,MAAI,mBAAmB,IAAI,EAAE,WAAW,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC1E,SAAO,gBAAgB,IAAI,eAAe,QAAQ,KAAK,OAAO,CAAC,2DAA2D,MAAM;AAClI;","names":[]}
@@ -15,29 +15,29 @@ import {
15
15
  scan,
16
16
  updatePost,
17
17
  writeModeNotices
18
- } from "./chunk-GCGMXA2O.js";
18
+ } from "./chunk-VJSQSLBM.js";
19
19
  import {
20
20
  describeWallet,
21
21
  resolveWalletProvider
22
- } from "./chunk-JVBMPU5G.js";
22
+ } from "./chunk-CPCX67TI.js";
23
23
  import {
24
24
  sanitizeForTerminal
25
- } from "./chunk-B676GPS2.js";
25
+ } from "./chunk-OLWTRUTS.js";
26
26
  import {
27
27
  resolveContextSettings,
28
28
  resolvePublishSettings
29
- } from "./chunk-IGHSLJUF.js";
29
+ } from "./chunk-VYOJOX4Z.js";
30
30
  import {
31
31
  UUID_RE,
32
32
  parseUsdToAtomic,
33
33
  toMoney
34
- } from "./chunk-736DW4V3.js";
34
+ } from "./chunk-EFWZPUTC.js";
35
35
  import {
36
36
  parsePublishModeFlag
37
- } from "./chunk-ELVDOTU7.js";
37
+ } from "./chunk-U6VPKMGC.js";
38
38
  import {
39
39
  CliError
40
- } from "./chunk-PAOVPSP6.js";
40
+ } from "./chunk-ZFJJ3EXC.js";
41
41
 
42
42
  // src/commands/edit.ts
43
43
  import { readFile } from "fs/promises";
@@ -211,10 +211,10 @@ function cardLines(card) {
211
211
  return lines;
212
212
  }
213
213
  function eligibilityLine(card) {
214
- if (card === void 0) return "No answer card (browse-only document).";
214
+ if (card === void 0) return "No answer card: ranks below every carded piece in agent search.";
215
215
  const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);
216
216
  if (card.cacheEligible) return "Answer card is search-eligible.";
217
- return missing.length > 0 ? `Answer card not search-eligible yet: ${missing.join(" ")}` : "Answer card is not search-eligible.";
217
+ return missing.length > 0 ? `Answer card incomplete, ranks below every complete card in agent search. To fix: ${missing.join(" ")}` : "Answer card incomplete, ranks below every complete card in agent search.";
218
218
  }
219
219
  function diffUpdate(stored, intent) {
220
220
  const lines = [];
@@ -611,4 +611,4 @@ function hasText(value) {
611
611
  export {
612
612
  runEdit
613
613
  };
614
- //# sourceMappingURL=chunk-YMUJZWHB.js.map
614
+ //# sourceMappingURL=chunk-4KG27W2S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/edit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag, type PublishMode } from '../lib/config';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { sanitizeForTerminal } from '../lib/output';\nimport {\n deriveCard,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n buildPostUpdateBody,\n getOwnPost,\n updatePost,\n type OwnPost,\n type OwnPostCard,\n type PostUpdateInput,\n type ResourceCardUpdate,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin edit <postId>`: the agent-side twin of the web answer-card panel. With\n * no change flags it READS the owner-scoped post and prints it; with change flags\n * it merge-updates via `PUT /api/posts/<id>` — omitted key = keep, `--clear` sends\n * the explicit null (or the empty container) the server's merge clears on, and an\n * array flag REPLACES the stored array wholesale (`--add-question` is the append\n * convenience that reads first and sends the merged array).\n *\n * The gates are publish's, deliberately: the same deterministic scan over the new\n * body + card text (a live secret hard-blocks in every mode) and the same\n * publish.mode consent cascade, because an edit ships content to the same public\n * page a publish does.\n *\n * Unlike publish, the wallet is touched BEFORE consent, and that is a real\n * tradeoff, not a technicality: the before→after summary the user approves can\n * only be built from the stored post, and reading it is owner-scoped. The read\n * changes nothing on the server and burns no nonce, but on first use it\n * establishes a session key, so one wallet signature and a delegation persisted to\n * `~/.tenjin/session.json` precede any approval. What that delegation can DO is\n * scoped to the run: a no-flag show mints `read`, and only an invocation that\n * intends to write asks for `read+write`. We accept the remaining cost, because\n * the alternative is asking a human to approve a diff we cannot show them.\n *\n * Exit codes: 0 success (and the read-only show), 2 usage, 3 needs_confirmation /\n * non-bypassable publish_blocked, 4 a write failure after approval.\n */\n\nexport interface EditArgs {\n /** The post uuid to edit. */\n postId: string;\n /** Card array flags: REPLACE the stored array wholesale. */\n question?: string[];\n task?: string[];\n /** Append convenience: read the stored array, add, dedupe, send the merged array. */\n addQuestion?: string[];\n addTask?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n /** Post fields. */\n title?: string;\n /** Post price, decimal USD at the edge (O1). */\n price?: string;\n /** A Markdown file whose body (frontmatter stripped) replaces the stored body. */\n body?: string;\n excerpt?: string;\n /** Card fields to clear (repeatable); see CLEAR_FIELDS. */\n clear?: string[];\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n}\n\nexport interface EditDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runEdit(\n args: EditArgs,\n ctx: CommandContext,\n deps: EditDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n\n if (!UUID_RE.test(args.postId)) {\n throw new CliError('USAGE', `Invalid post id: ${JSON.stringify(args.postId)}`, {\n fix: 'Pass the post uuid from `tenjin publish`’s receipt or your desk.',\n });\n }\n // A mistyped --mode must never silently land on a looser mode and apply an edit\n // unconfirmed; validate it at the edge, exactly as publish does.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n // Every edge check that can fail on the FLAGS alone runs before the wallet: a\n // typo must cost nothing, not a signature and a round trip.\n rejectEmptyValues(args);\n assertAppendExclusivity(args);\n const clears = parseClears(args);\n const cardFlags = cardFlagsFrom(args);\n const priceAtomic = args.price !== undefined ? parseUsdToAtomic(args.price) : undefined;\n const bodyFile = args.body !== undefined ? await readBodyFile(args.body) : undefined;\n const wantsChange = hasChangeFlags(args);\n\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n // Least privilege, decided before the wallet is asked for anything: a show is a\n // READ, so it mints a read-scoped delegation rather than leaving a write-capable\n // one on disk for a command that never writes. A cached read+write session still\n // serves it, so this costs no extra signature.\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n scope: wantsChange ? 'read+write' : 'read',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n const client = {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n const stored = await getOwnPost(args.postId, auth, client);\n if (!wantsChange) return showReceipt(stored);\n\n // The append path merges onto the STORED array (exact-string dedupe) and sends\n // the result: the server replaces arrays wholesale, so there is no append there.\n if (args.addQuestion !== undefined && args.addQuestion.length > 0) {\n cardFlags.question = appendUnique(storedList(stored, 'questionsAnswered'), args.addQuestion);\n }\n if (args.addTask !== undefined && args.addTask.length > 0) {\n cardFlags.task = appendUnique(storedList(stored, 'tasksSupported'), args.addTask);\n }\n\n // deriveCard validates the set fields against the server's bounds and reports\n // them under the same dotted `resource.<field>` keys the server would.\n const intent: PostUpdateInput = {\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(bodyFile !== undefined ? { bodyMd: bodyFile.body } : {}),\n ...(args.excerpt !== undefined ? { excerpt: args.excerpt } : {}),\n ...(priceAtomic !== undefined ? { priceAtomic } : {}),\n ...withClears(deriveCard({}, cardFlags), clears, stored.resource),\n };\n\n // Diff before deciding anything: a no-op edit is not an edit. With nothing left\n // after pruning there is nothing to confirm, nothing new to scan, and no reason\n // to burn a nonce on a write that changes nothing. Exit 0 with the current post.\n const { input, lines: changes } = diffUpdate(stored, intent);\n if (changes.length === 0) return noChangeReceipt(stored);\n // Bounds-check the pruned body here so a miss is USAGE before the consent\n // prompt; updatePost rebuilds the same body for the wire (pure, so identical).\n buildPostUpdateBody(input);\n\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each edit asks you once. Set auto to apply clean edits automatically',\n );\n\n // Gate parity with publish (#38): the source project's own git remote slugs are\n // private-by-default, so text quoting them warns. Markers derive from the\n // CONTENT's project — the body file's own directory when there is one, else the\n // working directory — never from wherever the shell happens to be.\n const markerRoot = args.body !== undefined ? dirname(resolve(cwd, args.body)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n // The scan covers exactly what this edit SHIPS: the typed text behind the keys\n // that survived pruning, plus the body file only when the body itself survived.\n // Scanning the raw flags instead would block on a value that prunes away — a\n // secret already public in the stored scope, restated verbatim, would refuse an\n // unrelated title change while the same flags alone exit 0. A secret in a\n // surviving value still blocks in every mode, never cleared by --yes.\n const findings = dedupeFindings([\n ...(input.bodyMd !== undefined ? scan(bodyFile?.raw ?? '', scanContext) : []),\n ...scan(shippedTypedText(args, input), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the new content (it is never masked away by --yes), then re-run.',\n details: { mode: settings.mode, findings: blocking.map(publicFinding) },\n });\n }\n\n const notes = editNotes(args, stored, bodyFile, clears);\n for (const line of [...notes, ...changes]) ctx.io.stderr.write(`${line}\\n`);\n\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, changes.length), {\n fix: 'Review the changes, then re-run with --yes.',\n details: {\n mode: settings.mode,\n postId: stored.id,\n title: sanitizeForTerminal(stored.title),\n changes,\n ...(notes.length > 0 ? { notes } : {}),\n findings: warns.map(publicFinding),\n },\n });\n }\n\n const updated = await updatePost(args.postId, input, auth, client);\n return updateReceipt(updated, changes, notes, settings.mode);\n}\n\n// ---------------------------------------------------------------------------\n// Receipts.\n// ---------------------------------------------------------------------------\n\n/** The read half of the loop: the stored post + card, owner view. */\nfunction showReceipt(post: OwnPost): CommandResult {\n const price = toMoney(post.price);\n const card = post.resource;\n const lines = [\n `${sanitizeForTerminal(post.title)} (${sanitizeForTerminal(post.status)}), ${price.usd} USD (${price.atomic} atomic)`,\n `url: ${sanitizeForTerminal(post.url)}`,\n ...(hasText(post.excerpt) ? [`excerpt: ${preview(post.excerpt)}`] : []),\n ...cardLines(card),\n eligibilityLine(card),\n ];\n return { data: post, humanLines: lines };\n}\n\n/**\n * The applied-update receipt. `changes` (and `notes`) are mirrored INTO the data\n * as well as printed, the way publish mirrors its stderr warnings into the\n * receipt: an MCP client gets a discard sink for stderr, so a summary that lives\n * only there is a summary it can never show the user. `changes: []` is the\n * unambiguous machine signal that nothing was written.\n */\nfunction updateReceipt(\n post: OwnPost,\n changes: string[],\n notes: string[],\n mode: PublishMode,\n): CommandResult {\n const card = post.resource;\n const lines = [\n `Updated ${sanitizeForTerminal(post.title)} → ${sanitizeForTerminal(post.url)}`,\n eligibilityLine(card),\n ...(post.warnings ?? []).map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n // `mode` is echoed because a per-call --mode (or the MCP `mode` argument) is\n // otherwise invisible in a transcript: the receipt would look identical\n // whether the caller loosened the gate for this run or not.\n data: { ...post, mode, changes, ...(notes.length > 0 ? { notes } : {}) },\n humanLines: lines,\n };\n}\n\n/** Nothing to write: the post as it stands, and an empty change list to prove it. */\nfunction noChangeReceipt(post: OwnPost): CommandResult {\n return {\n data: { ...post, changes: [] },\n humanLines: [\n `No changes: every value given already matches ${sanitizeForTerminal(post.title)}. Nothing was written.`,\n ],\n };\n}\n\n/** The card fields that are set, one per line; nothing for a post with no card. */\nfunction cardLines(card: OwnPostCard | undefined): string[] {\n if (card === undefined) return [];\n const lines: string[] = [];\n const list = (label: string, values: string[] | null | undefined): void => {\n if (values !== undefined && values !== null && values.length > 0) {\n lines.push(\n `${label} (${values.length}): ${values.map((v) => sanitizeForTerminal(v)).join(' | ')}`,\n );\n }\n };\n list('questionsAnswered', card.questionsAnswered);\n list('tasksSupported', card.tasksSupported);\n for (const [label, value] of [\n ['scope', card.scope],\n ['exclusions', card.exclusions],\n ['artifactType', card.artifactType],\n ['temporalMode', card.temporalMode],\n ['asOf', card.asOf],\n ['validUntil', card.validUntil],\n ['provenance', card.provenanceSummary],\n ['methodology', card.methodologySummary],\n ['supersedesPostId', card.supersedesPostId],\n ] as const) {\n if (hasText(value)) lines.push(`${label}: ${preview(value)}`);\n }\n if (card.appliesTo !== undefined && card.appliesTo !== null) {\n for (const [key, values] of Object.entries(card.appliesTo)) {\n lines.push(\n `appliesTo ${sanitizeForTerminal(key)}: ${values.map((v) => sanitizeForTerminal(v)).join(', ')}`,\n );\n }\n }\n return lines;\n}\n\nfunction eligibilityLine(card: OwnPostCard | undefined): string {\n if (card === undefined) return 'No answer card: ranks below every carded piece in agent search.';\n const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);\n if (card.cacheEligible) return 'Answer card is search-eligible.';\n return missing.length > 0\n ? `Answer card incomplete, ranks below every complete card in agent search. To fix: ${missing.join(' ')}`\n : 'Answer card incomplete, ranks below every complete card in agent search.';\n}\n\n// ---------------------------------------------------------------------------\n// The before→after summary.\n// ---------------------------------------------------------------------------\n\n/**\n * Diff what the flags ASK for against what is stored, and return both the terse\n * summary and an input pruned to the fields that actually move.\n *\n * Pruning is not cosmetic. A card key that rides along unchanged still counts as a\n * card write server-side, which re-runs the embedding for a card nobody edited;\n * and on a post with NO card, a lone `scope: null` mints an all-default card row,\n * turning a card-less post into a card-bearing one. Comparing first and\n * sending only the difference is what keeps `edit` idempotent.\n */\nfunction diffUpdate(\n stored: OwnPost,\n intent: PostUpdateInput,\n): { input: PostUpdateInput; lines: string[] } {\n const lines: string[] = [];\n const input: PostUpdateInput = {};\n\n // Both sides trimmed, because the server trims these before storing them: an\n // untrimmed compare would call \" x\" a change from \"x\" forever.\n const title = intent.title?.trim();\n if (title !== undefined && title !== stored.title) {\n input.title = title;\n lines.push(`title: ${preview(stored.title)} → ${preview(title)}`);\n }\n if (intent.priceAtomic !== undefined && intent.priceAtomic !== stored.price) {\n const before = toMoney(stored.price);\n const after = toMoney(intent.priceAtomic);\n input.priceAtomic = intent.priceAtomic;\n lines.push(\n `price: ${before.usd} USD (${before.atomic} atomic) → ${after.usd} USD (${after.atomic} atomic)`,\n );\n }\n if (intent.bodyMd !== undefined && intent.bodyMd !== stored.bodyMd) {\n input.bodyMd = intent.bodyMd;\n lines.push(`body: ${(stored.bodyMd ?? '').length} → ${intent.bodyMd.length} characters`);\n }\n const excerpt = intent.excerpt?.trim();\n if (excerpt !== undefined && excerpt !== (stored.excerpt ?? '')) {\n input.excerpt = excerpt;\n lines.push(`excerpt: ${preview(stored.excerpt)} → ${preview(excerpt)}`);\n }\n\n const card = diffCard(stored.resource, intent.resource);\n lines.push(...card.lines);\n if (card.card !== undefined) input.resource = card.card;\n\n // Empty means EMPTY: the caller reads no lines as \"this edit is a no-op\" and\n // skips the write, so a sentinel line here would report a change that isn't one.\n return { input, lines };\n}\n\n/**\n * How each card key is diffed. The Record over `keyof ResourceCardUpdate` is the\n * point: adding a field to the card type without saying how it diffs is a compile\n * error here, not a field that silently never reaches the wire. `none` marks a\n * field no flag and no clear can set today, so it can never appear in `next`;\n * giving one a flag means moving it to a real pass.\n */\ntype CardPass = 'list' | 'iso' | 'scalar' | 'map' | 'none';\nconst CARD_PASS = {\n questionsAnswered: 'list',\n tasksSupported: 'list',\n asOf: 'iso',\n validUntil: 'iso',\n scope: 'scalar',\n exclusions: 'scalar',\n artifactType: 'scalar',\n temporalMode: 'scalar',\n provenanceSummary: 'scalar',\n methodologySummary: 'scalar',\n supersedesPostId: 'scalar',\n appliesTo: 'map',\n mediaType: 'none',\n maintenanceCadence: 'none',\n reproductionMinutes: 'none',\n estimatedPaidInputCost: 'none',\n} as const satisfies Record<keyof ResourceCardUpdate, CardPass>;\n\n/** The card keys assigned to one pass, as a union of literal keys. */\ntype KeysIn<P extends CardPass> = {\n [K in keyof typeof CARD_PASS]: (typeof CARD_PASS)[K] extends P ? K : never;\n}[keyof typeof CARD_PASS];\n\nfunction keysIn<P extends CardPass>(pass: P): KeysIn<P>[] {\n return Object.entries(CARD_PASS)\n .filter(([, value]) => value === pass)\n .map(([key]) => key) as KeysIn<P>[];\n}\n\n/** The two card keys whose flag name differs from the field name. */\nconst CARD_LABEL: Partial<Record<keyof ResourceCardUpdate, string>> = {\n provenanceSummary: 'provenance',\n methodologySummary: 'methodology',\n};\nfunction cardLabel(key: keyof ResourceCardUpdate): string {\n return CARD_LABEL[key] ?? key;\n}\n\n/**\n * The card half of the diff. Every comparison treats an ABSENT stored value as\n * already-cleared, which is what makes clearing a field on a cardless post the\n * no-op it should be rather than a card-creating write.\n */\nfunction diffCard(\n stored: OwnPostCard | undefined,\n next: ResourceCardUpdate | undefined,\n): { card?: ResourceCardUpdate; lines: string[] } {\n const lines: string[] = [];\n const card: Record<string, unknown> = {};\n const keep = (key: keyof ResourceCardUpdate, value: unknown, line: string): void => {\n card[key] = value;\n lines.push(line);\n };\n if (next === undefined) return { lines };\n\n // Lists replace wholesale, so order counts; an absent stored list reads as empty.\n for (const key of keysIn('list')) {\n const after = next[key];\n if (after === undefined) continue;\n const old = stored?.[key] ?? [];\n if (sameList(old, after)) continue;\n const added = after.filter((v) => !old.includes(v));\n const detail =\n after.length === 0 ? ' (cleared)' : added.length > 0 ? ` (new: ${previewList(added)})` : '';\n keep(key, after, `${key}: ${old.length} → ${after.length}${detail}`);\n }\n\n // The timestamps compare as INSTANTS and are sent canonicalized. The server\n // echoes a timestamptz through toISOString(), while a flag carries whatever the\n // user typed, so \"2026-07-01T00:00:00Z\" and \"2026-07-01T00:00:00.000Z\" are the\n // same moment spelled two ways — comparing the spellings would re-write the\n // field on every single run.\n for (const key of keysIn('iso')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = isoInstant(stored?.[key]);\n const to = isoInstant(after);\n if (from === to) continue;\n keep(key, to, `${key}: ${preview(from)} → ${to === null ? '(cleared)' : preview(to)}`);\n }\n\n for (const key of keysIn('scalar')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = stored?.[key] ?? null;\n if (from === after) continue;\n keep(\n key,\n after,\n `${cardLabel(key)}: ${preview(from)} → ${after === null ? '(cleared)' : preview(after)}`,\n );\n }\n\n // appliesTo is one value, not a key count: a same-size swap (products=Base →\n // products=Vercel) has identical counts on both sides, so a count compare would\n // call a real change a no-op and a count RENDER would print it as one.\n for (const key of keysIn('map')) {\n const after = next[key];\n if (after === undefined) continue;\n const before = stored?.[key] ?? {};\n if (sameAppliesTo(before, after)) continue;\n keep(key, after, `${key}: ${appliesToPreview(before)} → ${appliesToPreview(after)}`);\n }\n\n return { ...(Object.keys(card).length > 0 ? { card: card as ResourceCardUpdate } : {}), lines };\n}\n\n/**\n * A timestamp as its canonical instant, so two spellings of one moment compare\n * equal. An unparseable value (never from a flag — validateIso ran — but possible\n * from a future server format) passes through rather than being silently dropped.\n */\nfunction isoInstant(value: string | null | undefined): string | null {\n if (value === undefined || value === null) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? new Date(ms).toISOString() : value;\n}\n\n/** Map equality: keys order-insensitive, each key's values order-sensitive. */\nfunction sameAppliesTo(a: Record<string, string[]>, b: Record<string, string[]>): boolean {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (!sameList(aKeys, bKeys)) return false;\n return aKeys.every((key) => sameList(a[key] ?? [], b[key] ?? []));\n}\n\n/** The advisory notes a --body edit needs, in the order a human reads them. */\nfunction editNotes(\n args: EditArgs,\n stored: OwnPost,\n bodyFile: BodyFile | undefined,\n clears: ClearField[],\n): string[] {\n if (bodyFile === undefined) return [];\n const notes: string[] = [];\n if (bodyFile.hadFrontmatter) {\n notes.push(\n 'note: frontmatter in the body file was ignored; metadata changes only through flags.',\n );\n }\n if (args.excerpt === undefined) {\n notes.push(\n `note: the excerpt stays as-is (${preview(stored.excerpt)}) and remains lexically indexed; the server does not re-derive it. Pass --excerpt to change it.`,\n );\n }\n // Only when asOf really is staying put: a run that clears it is already saying\n // so in the summary, and both lines together would contradict each other.\n const asOfMoves = args.asOf !== undefined || clears.includes('asOf');\n if (stored.resource?.temporalMode === 'snapshot' && !asOfMoves) {\n notes.push(\n `note: asOf is unchanged (${preview(stored.resource.asOf)}) on this snapshot card, and search freshness gating uses it. Pass --as-of to move it.`,\n );\n }\n return notes;\n}\n\n// ---------------------------------------------------------------------------\n// Flag parsing + validation.\n// ---------------------------------------------------------------------------\n\n/** The card fields `--clear` accepts, named as the flag that sets each one. */\nconst CLEAR_FIELDS = [\n 'scope',\n 'exclusions',\n 'asOf',\n 'validUntil',\n 'provenance',\n 'methodology',\n 'supersedesPostId',\n 'questionsAnswered',\n 'tasksSupported',\n 'appliesTo',\n] as const;\ntype ClearField = (typeof CLEAR_FIELDS)[number];\n\n/** clear name → the card key it targets. */\nconst CLEAR_KEY = {\n scope: 'scope',\n exclusions: 'exclusions',\n asOf: 'asOf',\n validUntil: 'validUntil',\n provenance: 'provenanceSummary',\n methodology: 'methodologySummary',\n supersedesPostId: 'supersedesPostId',\n questionsAnswered: 'questionsAnswered',\n tasksSupported: 'tasksSupported',\n appliesTo: 'appliesTo',\n} as const satisfies Record<ClearField, keyof ResourceCardUpdate>;\n\n/**\n * clear name → the value that clears its key server-side. Each value is typed as\n * the card field it lands on, so sending the wrong shape (a null where the merge\n * clears with `[]`, or an `[]` where it wants null) is a compile error, not a\n * validation_failed discovered in production.\n */\nconst CLEAR_VALUE: { [F in ClearField]: ResourceCardUpdate[(typeof CLEAR_KEY)[F]] } = {\n scope: null,\n exclusions: null,\n asOf: null,\n validUntil: null,\n provenance: null,\n methodology: null,\n supersedesPostId: null,\n questionsAnswered: [],\n tasksSupported: [],\n appliesTo: {},\n};\n\n/** clear name → the set-flags that would contradict it in the same invocation. */\nconst CLEAR_CONFLICTS: Record<ClearField, Array<keyof EditArgs>> = {\n scope: ['scope'],\n exclusions: ['exclusions'],\n asOf: ['asOf'],\n validUntil: ['validUntil'],\n provenance: ['provenance'],\n methodology: ['methodology'],\n supersedesPostId: [],\n questionsAnswered: ['question', 'addQuestion'],\n tasksSupported: ['task', 'addTask'],\n appliesTo: ['appliesTo'],\n};\n\n/** The CLI spelling of each arg key, for error messages. */\nconst FLAG_NAME: Record<string, string> = {\n question: '--question',\n task: '--task',\n addQuestion: '--add-question',\n addTask: '--add-task',\n scope: '--scope',\n exclusions: '--exclusions',\n appliesTo: '--applies-to',\n asOf: '--as-of',\n validUntil: '--valid-until',\n artifactType: '--artifact-type',\n temporalMode: '--temporal-mode',\n provenance: '--provenance',\n methodology: '--methodology',\n title: '--title',\n price: '--price',\n body: '--body',\n excerpt: '--excerpt',\n};\n\nconst CHANGE_KEYS: Array<keyof EditArgs> = [\n 'question',\n 'task',\n 'addQuestion',\n 'addTask',\n 'scope',\n 'exclusions',\n 'appliesTo',\n 'asOf',\n 'validUntil',\n 'artifactType',\n 'temporalMode',\n 'provenance',\n 'methodology',\n 'title',\n 'price',\n 'body',\n 'excerpt',\n 'clear',\n];\n\nfunction hasChangeFlags(args: EditArgs): boolean {\n return CHANGE_KEYS.some((key) => {\n const value = args[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\n/**\n * An explicit empty value is refused for every set-flag: `--scope \"\"` reads as\n * \"clear the scope\", but only `--clear scope` sends the null that clears it, and a\n * silently-sent empty string would set a blank field instead. One spelling per\n * intent, no ambiguity.\n */\nfunction rejectEmptyValues(args: EditArgs): void {\n for (const [key, flag] of Object.entries(FLAG_NAME)) {\n const value = args[key as keyof EditArgs];\n const empties =\n typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value.filter((v) => typeof v === 'string')\n : [];\n for (const v of empties) {\n if (v.trim().length === 0) {\n const clearable = (CLEAR_FIELDS as readonly string[]).includes(clearNameFor(key));\n throw new CliError('USAGE', `${flag} cannot be empty.`, {\n fix: clearable\n ? `Pass a value, or clear the field with \\`--clear ${clearNameFor(key)}\\`.`\n : 'Pass a value, or omit the flag to keep the stored one.',\n });\n }\n }\n }\n}\n\n/** The `--clear` name a set-flag arg key corresponds to (identity where they match). */\nfunction clearNameFor(key: string): string {\n if (key === 'question' || key === 'addQuestion') return 'questionsAnswered';\n if (key === 'task' || key === 'addTask') return 'tasksSupported';\n return key;\n}\n\nfunction assertAppendExclusivity(args: EditArgs): void {\n const both = (a: string[] | undefined, b: string[] | undefined): boolean =>\n a !== undefined && a.length > 0 && b !== undefined && b.length > 0;\n if (both(args.question, args.addQuestion)) {\n throw new CliError('USAGE', 'Pass either --question or --add-question, not both.', {\n fix: '--question replaces the stored questions; --add-question appends to them.',\n });\n }\n if (both(args.task, args.addTask)) {\n throw new CliError('USAGE', 'Pass either --task or --add-task, not both.', {\n fix: '--task replaces the stored tasks; --add-task appends to them.',\n });\n }\n}\n\nfunction parseClears(args: EditArgs): ClearField[] {\n const raw = args.clear ?? [];\n const out: ClearField[] = [];\n for (const name of raw) {\n if (!(CLEAR_FIELDS as readonly string[]).includes(name)) {\n throw new CliError('USAGE', `Cannot clear ${JSON.stringify(name)}.`, {\n fix: `Clearable fields: ${CLEAR_FIELDS.join(', ')}.`,\n });\n }\n const field = name as ClearField;\n for (const key of CLEAR_CONFLICTS[field]) {\n const value = args[key];\n const given = Array.isArray(value) ? value.length > 0 : value !== undefined;\n if (given) {\n throw new CliError(\n 'USAGE',\n `--clear ${field} contradicts ${FLAG_NAME[key as string] ?? String(key)}.`,\n { fix: 'Set the field or clear it, not both in the same run.' },\n );\n }\n }\n if (!out.includes(field)) out.push(field);\n }\n return out;\n}\n\nfunction cardFlagsFrom(args: EditArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The card this edit ASKS for: the validated set fields plus the clears. Built\n * from an allowlist (deriveCard's output keys and CLEAR_KEY) and never from a\n * spread of the GET, so a server-owned key (cacheEligible, cacheEligibleMissing,\n * schemaVersion) cannot reach a strictObject body that would reject it.\n *\n * What actually protects the server's D14 invariant (no card row on a card-less\n * post) is diffCard: it defaults an absent stored value to already-cleared, so a\n * clear on a post with no card compares equal and prunes away. Dropping the clears\n * here as well is a deliberate redundant backstop, one step earlier and local to\n * the one condition that matters, because the cost of that invariant breaking is a\n * plain document silently becoming card-bearing.\n */\nfunction withClears(\n set: ResourceCardInput | undefined,\n clears: ClearField[],\n stored: OwnPostCard | undefined,\n): { resource?: ResourceCardUpdate } {\n const applicable = stored !== undefined ? clears : [];\n if (set === undefined && applicable.length === 0) return {};\n const card: Record<string, unknown> = { ...(set ?? {}) };\n for (const name of applicable) {\n card[CLEAR_KEY[name]] = CLEAR_VALUE[name];\n }\n return Object.keys(card).length > 0 ? { resource: card as ResourceCardUpdate } : {};\n}\n\ninterface BodyFile {\n /** The whole file, frontmatter included; what the scan reads. */\n raw: string;\n /** The Markdown below the frontmatter; what becomes bodyMd. */\n body: string;\n hadFrontmatter: boolean;\n}\n\nasync function readBodyFile(file: string): Promise<BodyFile> {\n let raw: string;\n try {\n raw = await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin edit <id> --body post.md`.',\n cause: err,\n });\n }\n const { frontmatter, body } = parseFrontmatter(raw);\n return { raw, body, hadFrontmatter: Object.keys(frontmatter).length > 0 };\n}\n\nfunction storedList(post: OwnPost, key: 'questionsAnswered' | 'tasksSupported'): string[] {\n return post.resource?.[key] ?? [];\n}\n\n/** Append, preserving order, skipping exact-string duplicates already stored. */\nfunction appendUnique(stored: string[], additions: string[]): string[] {\n const out = [...stored];\n for (const item of additions) {\n if (!out.includes(item)) out.push(item);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Scan input + message shaping (publish's, over the edit's new content).\n// ---------------------------------------------------------------------------\n\n/**\n * The text this invocation actually SHIPS, and only that. Two filters, each\n * closing a way the gate could fire on text the edit does not publish:\n *\n * - the key must have survived pruning. A flag whose value already matches the\n * stored one changes nothing, so its text is not \"new content\" at all; blocking\n * on it refuses an edit over a secret that is already public and that no flag\n * here can remove.\n * - the value must be one the user TYPED. The append path contributes its added\n * strings, never the merged array it sends, for the same reason.\n *\n * Everything that does ship is scanned, so a secret in a surviving value blocks in\n * every mode, never cleared by --yes.\n */\nfunction shippedTypedText(args: EditArgs, input: PostUpdateInput): string {\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n if (input.title !== undefined) add(args.title);\n if (input.excerpt !== undefined) add(args.excerpt);\n\n const card = input.resource;\n if (card === undefined) return parts.join('\\n');\n if (card.scope !== undefined) add(args.scope);\n if (card.exclusions !== undefined) add(args.exclusions);\n if (card.provenanceSummary !== undefined) add(args.provenance);\n if (card.methodologySummary !== undefined) add(args.methodology);\n if (card.asOf !== undefined) add(args.asOf);\n if (card.validUntil !== undefined) add(args.validUntil);\n if (card.questionsAnswered !== undefined) {\n for (const item of args.question ?? args.addQuestion ?? []) add(item);\n }\n if (card.tasksSupported !== undefined) {\n for (const item of args.task ?? args.addTask ?? []) add(item);\n }\n if (card.appliesTo !== undefined && args.appliesTo !== undefined) {\n // The parsed values, matching what actually ships on the card.\n for (const values of Object.values(parseAppliesToFlags(args.appliesTo))) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Edit blocked: the new content contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, changeCount: number): string {\n return warnCount > 0\n ? `Edit needs confirmation: ${changeCount} change(s), ${warnCount} finding(s).`\n : `Edit needs confirmation: ${changeCount} change(s).`;\n}\n\n// ---------------------------------------------------------------------------\n// Small formatting helpers.\n// ---------------------------------------------------------------------------\n\nconst PREVIEW_MAX = 60;\n/** A whole rendered line's budget: a max-size card is 8 keys × 20 × 120 chars. */\nconst LINE_MAX = 200;\n\n/** Terminal-safe, whitespace-collapsed, and capped: the one place values are cut. */\nfunction clip(value: string, max = PREVIEW_MAX): string {\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n return clean.length > max ? `${clean.slice(0, max)}…` : clean;\n}\n\n/** A short, terminal-safe rendering of a stored or new value for the summary. */\nfunction preview(value: string | null | undefined): string {\n if (value === undefined || value === null || value.length === 0) return '(unset)';\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n if (clean.length === 0) return '(unset)';\n return clean.length > PREVIEW_MAX\n ? `${JSON.stringify(clean.slice(0, PREVIEW_MAX))}…`\n : JSON.stringify(clean);\n}\n\nfunction previewList(values: string[]): string {\n return values.map((v) => preview(v)).join(', ');\n}\n\n/**\n * `products=Base|Vercel, runtimes=node` — the VALUES, so a swap reads as a swap.\n * Every value takes the same 60-char cap the rest of the summary uses, and the\n * whole rendering is capped too: a full-size card would otherwise put ~19KB on one\n * stderr line.\n */\nfunction appliesToPreview(appliesTo: Record<string, string[]>): string {\n const entries = Object.entries(appliesTo);\n if (entries.length === 0) return '(unset)';\n const rendered = entries\n .map(([key, values]) => `${clip(key)}=${values.map((v) => clip(v)).join('|')}`)\n .join(', ');\n return clip(rendered, LINE_MAX);\n}\n\nfunction sameList(a: string[], b: string[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction hasText(value: string | null | undefined): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBA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AAE,KAAK;AACnE,SAAO,MAAM,SAAS,MAAM,GAAG,MAAM,MAAM,GAAG,GAAG,CAAC,WAAM;AAC1D;AAGA,SAAS,QAAQ,OAA0C;AACzD,MAAI,UAAU,UAAa,UAAU,QAAQ,MAAM,WAAW,EAAG,QAAO;AACxE,QAAM,QAAQ,oBAAoB,KAAK,EAAE,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACnE,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,SAAO,MAAM,SAAS,cAClB,GAAG,KAAK,UAAU,MAAM,MAAM,GAAG,WAAW,CAAC,CAAC,WAC9C,KAAK,UAAU,KAAK;AAC1B;AAEA,SAAS,YAAY,QAA0B;AAC7C,SAAO,OAAO,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC,EAAE,KAAK,IAAI;AAChD;AAQA,SAAS,iBAAiB,WAA6C;AACrE,QAAM,UAAU,OAAO,QAAQ,SAAS;AACxC,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,WAAW,QACd,IAAI,CAAC,CAAC,KAAK,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAC7E,KAAK,IAAI;AACZ,SAAO,KAAK,UAAU,QAAQ;AAChC;AAEA,SAAS,SAAS,GAAa,GAAsB;AACnD,SAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC,CAAC;AAC9D;AAEA,SAAS,QAAQ,OAA2C;AAC1D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;","names":[]}
@@ -1,21 +1,20 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- package_default
4
- } from "./chunk-CA3JV7FX.js";
3
+ composeUserAgent
4
+ } from "./chunk-3GL2Z5QK.js";
5
5
  import {
6
6
  CliError
7
- } from "./chunk-PAOVPSP6.js";
8
-
9
- // src/lib/client-meta.ts
10
- var TENJIN_USER_AGENT = `tenjin-cli/${package_default.version} (+https://tenjin.blog)`;
7
+ } from "./chunk-ZFJJ3EXC.js";
11
8
 
12
9
  // src/lib/http.ts
13
- function applyUserAgent(headers) {
14
- headers.set("user-agent", TENJIN_USER_AGENT);
10
+ function applyUserAgent(headers, callerUserAgent) {
11
+ headers.set("user-agent", composeUserAgent({ caller: callerUserAgent }));
15
12
  return headers;
16
13
  }
17
- function withUserAgent(callerHeaders) {
18
- return Object.fromEntries(applyUserAgent(new Headers(callerHeaders ?? {})).entries());
14
+ function withUserAgent(callerHeaders, callerUserAgent) {
15
+ return Object.fromEntries(
16
+ applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries()
17
+ );
19
18
  }
20
19
  var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
21
20
  "sign-in-with-x",
@@ -39,7 +38,7 @@ async function fetchJson(url, opts) {
39
38
  try {
40
39
  res = await doFetch(url, {
41
40
  signal: controller.signal,
42
- headers: withUserAgent(opts.headers)
41
+ headers: withUserAgent(opts.headers, opts.callerUserAgent)
43
42
  });
44
43
  } catch (err) {
45
44
  return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
@@ -103,7 +102,7 @@ function prepareRequest(url, opts) {
103
102
  }
104
103
  const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
105
104
  if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
106
- const headers = Object.fromEntries(applyUserAgent(merged).entries());
105
+ const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
107
106
  const signed = carriesSignedMaterial(headers);
108
107
  return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };
109
108
  } catch (err) {
@@ -174,6 +173,7 @@ async function httpRequest(url, opts) {
174
173
  status: res.status,
175
174
  header: (name) => res.headers.get(name) ?? void 0,
176
175
  json,
176
+ text,
177
177
  ...requestId !== void 0 ? { requestId } : {}
178
178
  };
179
179
  } finally {
@@ -196,4 +196,4 @@ export {
196
196
  httpRequest,
197
197
  fetchFailureToCliError
198
198
  };
199
- //# sourceMappingURL=chunk-SPUORKD7.js.map
199
+ //# sourceMappingURL=chunk-5QQTYWEU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/http.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n}\n\n/**\n * The one place the identity is written for anything that can import it; both\n * transports funnel their Headers through it, so a third entry point on this\n * side cannot ship without it. The generated hook scripts are the one request\n * path that cannot reach here, and they carry their own mirrored composer\n * (`lib/hook-scripts.ts`) rather than an exemption. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(\n callerHeaders?: Record<string, string>,\n callerUserAgent?: string,\n): Record<string, string> {\n return Object.fromEntries(\n applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries(),\n );\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect';\n status?: number;\n requestId?: string;\n message: string;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n headers: withUserAgent(opts.headers, opts.callerUserAgent),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** INTERNAL; see `FetchJsonOptions.callerUserAgent`. */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n /** The raw body text; what a non-JSON endpoint actually said (`pay` delivers it). */\n text: string;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n text,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"],"mappings":";;;;;;;;;AAsCA,SAAS,eAAe,SAAkB,iBAAmC;AAC3E,UAAQ,IAAI,cAAc,iBAAiB,EAAE,QAAQ,gBAAgB,CAAC,CAAC;AACvE,SAAO;AACT;AAGA,SAAS,cACP,eACA,iBACwB;AACxB,SAAO,OAAO;AAAA,IACZ,eAAe,IAAI,QAAQ,iBAAiB,CAAC,CAAC,GAAG,eAAe,EAAE,QAAQ;AAAA,EAC5E;AACF;AAoDA,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,sBAAsB,SAA0C;AACvE,SAAO,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC,SAAS,mBAAmB,IAAI,KAAK,YAAY,CAAC,CAAC;AACvF;AAIA,eAAsB,UAAU,KAAa,MAAkD;AAC7F,QAAM,UAAU,KAAK,aAAa;AAClC,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,WAAW;AAIf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,eAAW,MAAM;AAAA,EACnB,GAAG,KAAK,SAAS;AAEjB,MAAI;AACF,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ,WAAW;AAAA,QACnB,SAAS,cAAc,KAAK,SAAS,KAAK,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;AAAA,MACA,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD;AAAA,EACF,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AAcO,SAAS,uBACd,SACA,OAAiC,CAAC,GACxB;AACV,QAAM,OACJ,QAAQ,SAAS,aAAa,QAAQ,SAAS,YAC3C,kBACA,QAAQ,SAAS,iBACf,sBACA;AACR,SAAO,IAAI,SAAS,MAAM,QAAQ,SAAS;AAAA,IACzC,GAAI,KAAK,QAAQ,SAAY,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;AAAA,IAClD,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,EAChE,CAAC;AACH;AAEA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":[]}
@@ -0,0 +1,21 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/session.ts
4
+ function readSessionId(env = process.env) {
5
+ return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);
6
+ }
7
+ function firstNonEmpty(raw) {
8
+ if (typeof raw !== "string") return void 0;
9
+ const trimmed = raw.trim();
10
+ return trimmed.length > 0 ? trimmed : void 0;
11
+ }
12
+ function ownedByThisSession(entrySessionId, sessionId) {
13
+ if (sessionId === void 0) return true;
14
+ return entrySessionId === void 0 || entrySessionId === sessionId;
15
+ }
16
+
17
+ export {
18
+ readSessionId,
19
+ ownedByThisSession
20
+ };
21
+ //# sourceMappingURL=chunk-65DTCCJ7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/session.ts"],"sourcesContent":["/**\n * The harness session a command belongs to: `search` stamps entries with it and\n * `outcome --all-open` sweeps only this session's. ONE COPY, because a sweep and\n * the nag that named it must agree on what \"this session\" means.\n *\n * TENJIN_SESSION_ID is the operator override; CLAUDE_CODE_SESSION_ID is what\n * Claude Code exports to the Bash subprocess a `tenjin search` runs as, to the\n * stdio MCP server, and as the `session_id` the hook scripts read on stdin, so\n * all three stamp identically. Observed rather than documented, hence a\n * fallback: on a harness exporting neither this stays undefined.\n */\nexport function readSessionId(env: NodeJS.ProcessEnv = process.env): string | undefined {\n return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);\n}\n\nfunction firstNonEmpty(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Whether an entry is this session's business, mirroring the Stop hook's\n * `ownedByThisSession`. SCOPED WHEN KNOWN, GLOBAL WHEN NOT: a differently\n * stamped entry belongs to that session, and an unstamped one stays in scope,\n * because scoping must never make a loop unreachable everywhere at once.\n */\nexport function ownedByThisSession(\n entrySessionId: string | undefined,\n sessionId: string | undefined,\n): boolean {\n if (sessionId === undefined) return true;\n return entrySessionId === undefined || entrySessionId === sessionId;\n}\n"],"mappings":";;;AAWO,SAAS,cAAc,MAAyB,QAAQ,KAAyB;AACtF,SAAO,cAAc,IAAI,iBAAiB,KAAK,cAAc,IAAI,sBAAsB;AACzF;AAEA,SAAS,cAAc,KAA6C;AAClE,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAQO,SAAS,mBACd,gBACA,WACS;AACT,MAAI,cAAc,OAAW,QAAO;AACpC,SAAO,mBAAmB,UAAa,mBAAmB;AAC5D;","names":[]}