tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.31
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.
- package/NOTICE.md +54 -7
- package/README.md +100 -266
- package/dist/{_esm-FEASBWRP.js → _esm-MEXZI5DL.js} +9 -10
- package/dist/alive-J64H46HI.js +31 -0
- package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-27EPWVOY.js +108 -0
- package/dist/chunk-27EPWVOY.js.map +1 -0
- package/dist/chunk-2SNUOHAT.js +75 -0
- package/dist/chunk-2SNUOHAT.js.map +1 -0
- package/dist/{chunk-Z6MFJV5Z.js → chunk-2XLC3AEX.js} +857 -504
- package/dist/chunk-2XLC3AEX.js.map +1 -0
- package/dist/chunk-3623BLPV.js +184 -0
- package/dist/chunk-3623BLPV.js.map +1 -0
- package/dist/chunk-3UCIG4TG.js +65 -0
- package/dist/chunk-3UCIG4TG.js.map +1 -0
- package/dist/chunk-4ZZO6ULA.js +151 -0
- package/dist/chunk-4ZZO6ULA.js.map +1 -0
- package/dist/chunk-5C32RLTA.js +115 -0
- package/dist/chunk-5C32RLTA.js.map +1 -0
- package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5K5W4S66.js +105 -0
- package/dist/chunk-5K5W4S66.js.map +1 -0
- package/dist/chunk-5MARFNSB.js +2018 -0
- package/dist/chunk-5MARFNSB.js.map +1 -0
- package/dist/{chunk-CYOF7ROH.js → chunk-6E5R45ZO.js} +3 -3
- package/dist/chunk-77TCKDEC.js +1987 -0
- package/dist/chunk-77TCKDEC.js.map +1 -0
- package/dist/chunk-7EKYXMUO.js +7536 -0
- package/dist/chunk-7EKYXMUO.js.map +1 -0
- package/dist/chunk-7Q5FDF65.js +159 -0
- package/dist/chunk-7Q5FDF65.js.map +1 -0
- package/dist/chunk-7QKHZQKW.js +1680 -0
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/{chunk-MUBUQVC3.js → chunk-7WEQQJLG.js} +6 -5
- package/dist/{chunk-MUBUQVC3.js.map → chunk-7WEQQJLG.js.map} +1 -1
- package/dist/chunk-7WU4OPLP.js +244 -0
- package/dist/chunk-7WU4OPLP.js.map +1 -0
- package/dist/chunk-7ZRL2LBQ.js +192 -0
- package/dist/chunk-7ZRL2LBQ.js.map +1 -0
- package/dist/chunk-A36LQPHV.js +29 -0
- package/dist/chunk-A36LQPHV.js.map +1 -0
- package/dist/chunk-AGZ7PJKY.js +326 -0
- package/dist/chunk-AGZ7PJKY.js.map +1 -0
- package/dist/chunk-AKWGE6JQ.js +49 -0
- package/dist/chunk-AKWGE6JQ.js.map +1 -0
- package/dist/chunk-B7HUUJOK.js +29 -0
- package/dist/chunk-B7HUUJOK.js.map +1 -0
- package/dist/{chunk-S3IGX57D.js → chunk-BL3332HQ.js} +290 -7361
- package/dist/chunk-BL3332HQ.js.map +1 -0
- package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
- package/dist/chunk-D65GNPS3.js +12708 -0
- package/dist/chunk-D65GNPS3.js.map +1 -0
- package/dist/chunk-DOQGNFHM.js +121 -0
- package/dist/chunk-DOQGNFHM.js.map +1 -0
- package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
- package/dist/chunk-FW75G2W4.js +406 -0
- package/dist/chunk-FW75G2W4.js.map +1 -0
- package/dist/chunk-GA7JETVM.js +150 -0
- package/dist/chunk-GA7JETVM.js.map +1 -0
- package/dist/chunk-I3EQFHCD.js +175 -0
- package/dist/chunk-I3EQFHCD.js.map +1 -0
- package/dist/chunk-JKKAIPTU.js +108 -0
- package/dist/chunk-JKKAIPTU.js.map +1 -0
- package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-NCE5NSN6.js → chunk-K3I7C2MO.js} +142 -12
- package/dist/chunk-K3I7C2MO.js.map +1 -0
- package/dist/chunk-K72RURN3.js +239 -0
- package/dist/chunk-K72RURN3.js.map +1 -0
- package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-KOGZDMHO.js +21 -0
- package/dist/chunk-KOGZDMHO.js.map +1 -0
- package/dist/chunk-KXQ4UIP7.js +228 -0
- package/dist/chunk-KXQ4UIP7.js.map +1 -0
- package/dist/chunk-KXVP2VKA.js +194 -0
- package/dist/chunk-KXVP2VKA.js.map +1 -0
- package/dist/chunk-LEFIX6RS.js +100 -0
- package/dist/chunk-LEFIX6RS.js.map +1 -0
- package/dist/chunk-LHHMV4GU.js +27 -0
- package/dist/chunk-LHHMV4GU.js.map +1 -0
- package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/chunk-MNXS2U45.js +1768 -0
- package/dist/chunk-MNXS2U45.js.map +1 -0
- package/dist/{chunk-UGX7YPX2.js → chunk-NEFNKLBE.js} +9 -11
- package/dist/{chunk-UGX7YPX2.js.map → chunk-NEFNKLBE.js.map} +1 -1
- package/dist/chunk-OHRR5OYM.js +63 -0
- package/dist/chunk-OHRR5OYM.js.map +1 -0
- package/dist/chunk-ORWL5BSN.js +269 -0
- package/dist/chunk-ORWL5BSN.js.map +1 -0
- package/dist/chunk-P4NH7OUK.js +398 -0
- package/dist/chunk-P4NH7OUK.js.map +1 -0
- package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-QSCPK4F5.js +145 -0
- package/dist/chunk-QSCPK4F5.js.map +1 -0
- package/dist/chunk-QXP3Z3JN.js +131 -0
- package/dist/chunk-QXP3Z3JN.js.map +1 -0
- package/dist/{chunk-XJIW7USF.js → chunk-R5LCN54M.js} +118 -9
- package/dist/chunk-R5LCN54M.js.map +1 -0
- package/dist/chunk-S4SAZ7OD.js +30 -0
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/chunk-SJLTEINJ.js +117 -0
- package/dist/chunk-SJLTEINJ.js.map +1 -0
- package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/chunk-UKY4CHNC.js +498 -0
- package/dist/chunk-UKY4CHNC.js.map +1 -0
- package/dist/chunk-UQUOVWBG.js +114 -0
- package/dist/chunk-UQUOVWBG.js.map +1 -0
- package/dist/chunk-V6BSF6OC.js +260 -0
- package/dist/chunk-V6BSF6OC.js.map +1 -0
- package/dist/chunk-WJXLQXJY.js +43 -0
- package/dist/chunk-WJXLQXJY.js.map +1 -0
- package/dist/chunk-WK7F3B2E.js +114 -0
- package/dist/chunk-WK7F3B2E.js.map +1 -0
- package/dist/chunk-XKESD27X.js +10 -0
- package/dist/chunk-XKESD27X.js.map +1 -0
- package/dist/chunk-XQJXNMSB.js +23 -0
- package/dist/chunk-XQJXNMSB.js.map +1 -0
- package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/chunk-Y527D4TV.js +56 -0
- package/dist/chunk-Y527D4TV.js.map +1 -0
- package/dist/chunk-YFPY4ONH.js +127 -0
- package/dist/chunk-YFPY4ONH.js.map +1 -0
- package/dist/{chunk-OYMYCW7J.js → chunk-YVFXE7RR.js} +606 -97
- package/dist/chunk-YVFXE7RR.js.map +1 -0
- package/dist/clack-EZ7TDWQU.js +19 -0
- package/dist/claude-cli-2YKABJJZ.js +31 -0
- package/dist/{cli-SBXI5AMS.js → cli-D5OE3URZ.js} +458 -218
- package/dist/cli-D5OE3URZ.js.map +1 -0
- package/dist/codex-event-PPNVRRDH.js +16 -0
- package/dist/codex-host-2RJOJW2B.js +28 -0
- package/dist/codex-install-UUZ6QMBQ.js +221 -0
- package/dist/codex-install-UUZ6QMBQ.js.map +1 -0
- package/dist/config-ZD4OB2DO.js +51 -0
- package/dist/dist-3LOO6M4U.js +2842 -0
- package/dist/dist-3LOO6M4U.js.map +1 -0
- package/dist/doctor-KBR34Q4B.js +601 -0
- package/dist/doctor-KBR34Q4B.js.map +1 -0
- package/dist/env-proxy-XL4P73MZ.js +15 -0
- package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/ethersCompat-Df4a6QIZ-THAVUGIJ.js.map +1 -0
- package/dist/fund-5ITKQGYF.js +372 -0
- package/dist/fund-5ITKQGYF.js.map +1 -0
- package/dist/hook-command-4TYCHHRL.js +39 -0
- package/dist/hook-command-4TYCHHRL.js.map +1 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +15 -0
- package/dist/hosts/claude/tenjin/.mcp.json +12 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +224 -0
- package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
- package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
- package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
- package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
- package/dist/hosts/codex/tenjin/.mcp.json +12 -0
- package/dist/hosts/codex/tenjin/hooks/hooks.json +52 -0
- package/dist/hosts-FWZOV26H.js +216 -0
- package/dist/hosts-FWZOV26H.js.map +1 -0
- package/dist/index.js +21 -2
- package/dist/index.js.map +1 -1
- package/dist/install-XWGE4Q7L.js +77 -0
- package/dist/install-XWGE4Q7L.js.map +1 -0
- package/dist/install-identity-K7EJIQFP.js +30 -0
- package/dist/install-identity-K7EJIQFP.js.map +1 -0
- package/dist/install-wallet-XQ6XFZV4.js +117 -0
- package/dist/install-wallet-XQ6XFZV4.js.map +1 -0
- package/dist/mcp-3LIJSSJB.js +13553 -0
- package/dist/mcp-3LIJSSJB.js.map +1 -0
- package/dist/package-ZKQFDWLE.js +37 -0
- package/dist/package-ZKQFDWLE.js.map +1 -0
- package/dist/paths-POPTXJO6.js +61 -0
- package/dist/paths-POPTXJO6.js.map +1 -0
- package/dist/pay-WHBERZ3W.js +55 -0
- package/dist/pay-WHBERZ3W.js.map +1 -0
- package/dist/payments-KVICEKD2.js +110 -0
- package/dist/payments-KVICEKD2.js.map +1 -0
- package/dist/plugin-registration-5TIA564H.js +54 -0
- package/dist/plugin-registration-5TIA564H.js.map +1 -0
- package/dist/redact-6W23GGJC.js +15 -0
- package/dist/redact-6W23GGJC.js.map +1 -0
- package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
- package/dist/send-7G7Y7DLN.js +228 -0
- package/dist/send-7G7Y7DLN.js.map +1 -0
- package/dist/status-OF7RH5HM.js +120 -0
- package/dist/status-OF7RH5HM.js.map +1 -0
- package/dist/status-line-XOUE6MPL.js +90 -0
- package/dist/status-line-XOUE6MPL.js.map +1 -0
- package/dist/uninstall-JXUAFNDB.js +158 -0
- package/dist/uninstall-JXUAFNDB.js.map +1 -0
- package/dist/update-ZKUERSO2.js +44 -0
- package/dist/update-ZKUERSO2.js.map +1 -0
- package/dist/usdc-OGOGEHV2.js +40 -0
- package/dist/usdc-OGOGEHV2.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-S3DA7DFW.js} +5 -5
- package/dist/viemAdapter-By13KInL-S3DA7DFW.js.map +1 -0
- package/dist/wallet-2HA6W4R4.js +43 -0
- package/dist/wallet-2HA6W4R4.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +196 -0
- package/docs/safety-model.md +59 -0
- package/docs/troubleshooting.md +13 -0
- package/package.json +28 -19
- package/LICENSE +0 -21
- package/dist/buy-EE6SEXP6.js +0 -1598
- package/dist/buy-EE6SEXP6.js.map +0 -1
- package/dist/candidate-ERMSYYQZ.js +0 -127
- package/dist/candidate-ERMSYYQZ.js.map +0 -1
- package/dist/chunk-3OV7E5G5.js +0 -18
- package/dist/chunk-3OV7E5G5.js.map +0 -1
- package/dist/chunk-4ONXEEQL.js +0 -152
- package/dist/chunk-4ONXEEQL.js.map +0 -1
- package/dist/chunk-662MSGZB.js +0 -286
- package/dist/chunk-662MSGZB.js.map +0 -1
- package/dist/chunk-7KUW4MJD.js +0 -59
- package/dist/chunk-7KUW4MJD.js.map +0 -1
- package/dist/chunk-AWPAWHNX.js +0 -333
- package/dist/chunk-AWPAWHNX.js.map +0 -1
- package/dist/chunk-DXTQ3CSI.js +0 -171
- package/dist/chunk-DXTQ3CSI.js.map +0 -1
- package/dist/chunk-ESPNTPQ2.js +0 -207
- package/dist/chunk-ESPNTPQ2.js.map +0 -1
- package/dist/chunk-FJPLRISB.js +0 -79
- package/dist/chunk-FJPLRISB.js.map +0 -1
- package/dist/chunk-GO75V3NZ.js +0 -160
- package/dist/chunk-GO75V3NZ.js.map +0 -1
- package/dist/chunk-JPHG2JW3.js +0 -96
- package/dist/chunk-JPHG2JW3.js.map +0 -1
- package/dist/chunk-NCE5NSN6.js.map +0 -1
- package/dist/chunk-OYMYCW7J.js.map +0 -1
- package/dist/chunk-RY4XKNV3.js +0 -140
- package/dist/chunk-RY4XKNV3.js.map +0 -1
- package/dist/chunk-S3IGX57D.js.map +0 -1
- package/dist/chunk-TLCMMYLY.js +0 -126
- package/dist/chunk-TLCMMYLY.js.map +0 -1
- package/dist/chunk-UO22YNY4.js +0 -69
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-XHC6FCGZ.js +0 -261
- package/dist/chunk-XHC6FCGZ.js.map +0 -1
- package/dist/chunk-XJIW7USF.js.map +0 -1
- package/dist/chunk-YBMMV4Y4.js.map +0 -1
- package/dist/chunk-YN5SHIXQ.js +0 -126
- package/dist/chunk-YN5SHIXQ.js.map +0 -1
- package/dist/chunk-Z52RA3NC.js +0 -137
- package/dist/chunk-Z52RA3NC.js.map +0 -1
- package/dist/chunk-Z6MFJV5Z.js.map +0 -1
- package/dist/cli-SBXI5AMS.js.map +0 -1
- package/dist/config-VELDKLHY.js +0 -21
- package/dist/doctor-T3KWNNP2.js +0 -20
- package/dist/inspect-LMKOXE4Y.js +0 -96
- package/dist/inspect-LMKOXE4Y.js.map +0 -1
- package/dist/install-LEX3ENQ6.js +0 -387
- package/dist/install-LEX3ENQ6.js.map +0 -1
- package/dist/lookup-ZPN2Q67N.js +0 -129
- package/dist/lookup-ZPN2Q67N.js.map +0 -1
- package/dist/outcome-N7TAK6WR.js +0 -66
- package/dist/outcome-N7TAK6WR.js.map +0 -1
- package/dist/publish-BKBQQAW4.js +0 -1478
- package/dist/publish-BKBQQAW4.js.map +0 -1
- package/dist/usdc-JIAJW4SV.js +0 -22
- package/dist/wallet-CWEMYVIH.js +0 -179
- package/dist/wallet-CWEMYVIH.js.map +0 -1
- package/dist/wallet-PA54CRBL.js +0 -30
- package/skills/tenjin/SKILL.md +0 -199
- package/skills/tenjin-publish/SKILL.md +0 -111
- package/skills/tenjin-search/SKILL.md +0 -133
- /package/dist/{_esm-FEASBWRP.js.map → _esm-MEXZI5DL.js.map} +0 -0
- /package/dist/{ccip-NQXCEK2U.js.map → alive-J64H46HI.js.map} +0 -0
- /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-CYOF7ROH.js.map → chunk-6E5R45ZO.js.map} +0 -0
- /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
- /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{doctor-T3KWNNP2.js.map → clack-EZ7TDWQU.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
- /package/dist/{secp256k1-N3ZHU7LB.js.map → codex-event-PPNVRRDH.js.map} +0 -0
- /package/dist/{usdc-JIAJW4SV.js.map → codex-host-2RJOJW2B.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → config-ZD4OB2DO.js.map} +0 -0
- /package/dist/{wallet-PA54CRBL.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/grade.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/**\n * Did the agent USE what a hook arm showed it? The transcript is the only place\n * that answer exists.\n *\n * The arms record what they delivered (`fires`/`legs`), and the shelf records\n * what it served, but neither can see what happened next: the finding lands as\n * additional context in the agent's turn, and from there it is either acted on\n * or it is not. Nobody reports that, so without this the loop has no measure of\n * its own precision.\n *\n * WHAT COUNTS AS EVIDENCE, and why it is only ever a TOOL INPUT. An agent that\n * says \"as the Tenjin note suggests\" in prose has said nothing checkable — the\n * words are cheap, the sentence is generated beside a hundred others, and prose\n * agreeing with an injection is exactly what an injection makes likely whether\n * or not it helped. A tool call is a decision the agent spent something on. So\n * this reads two kinds of row and no others: the `hook_additional_context`\n * attachment that carries the injection (the anchor), and every later\n * `tool_use` block's input, serialized whole so a command, an edit's new text\n * and a written file all read the same way.\n *\n * THREE VERDICTS FOR \"USED\", TWO WEAK. Explicit `tenjin read|inspect <id>`, or\n * the injected url appearing in a tool input, is the agent following the\n * pointer: that is `read`, and it counts anywhere later in the session,\n * because a piece bought twenty tool calls after it was shown is still a piece\n * the injection sold. A backtick span copied out of the injected text is much\n * weaker — it may be a command the agent would have run anyway — so it counts\n * only inside {@link SPAN_WINDOW} tool calls of the anchor, needs at least two\n * words, and is reported to the shelf as `partially_used` rather than `used`.\n * `likely` is weaker again: a command head or file basename named anywhere in\n * the note's prose, with no backticks at all, matched the same way and ranked\n * below `span` — see {@link likelyTokens}.\n *\n * A SPAN OR A LIKELY TOKEN IS EXCLUDED WHEN THE SESSION ALREADY USED IT BEFORE\n * THE INJECTION (tenjin-agent#254a). Boilerplate a machine writes into every\n * subagent work order — `CI=true pnpm format:check` and the like — will always\n * reappear in the next tool call whether or not the injection ran, so a match\n * that cannot see behind the anchor cannot tell \"copied because shown\" from\n * \"was going to type this anyway\". `judge()` is handed the {@link SPAN_WINDOW}\n * tool calls BEFORE the anchor as well as after, and a candidate already\n * present there earns no credit — matched at a token boundary, not by plain\n * substring, so a longer pre-injection token cannot erase credit for a\n * shorter genuine one. This applies to `span` and `likely` only: `read` is a\n * command naming this specific piece, which nothing pre-injection could have\n * done by coincidence.\n *\n * NOTHING IS NOT REJECTION UNTIL THE SESSION IS OVER. A row whose session is\n * still running has simply not been answered yet, and grading it `rejected`\n * would post a verdict the next tool call could contradict. So \"nothing matched\"\n * becomes `rejected` only once the session has ended — `sessions.ended_at`, or a\n * transcript nothing has written to for {@link ENDED_AFTER_MS}.\n *\n * RELAYED ROWS ANCHOR ON THE FIRST TOOL CALL. The subagent arm hands its finding\n * to a child at SubagentStart, and that text reaches no transcript at all: the\n * child is given it as its opening context, and neither the parent's file nor\n * the child's records a `hook_additional_context` row for it. So there is no\n * anchor to find, and there does not need to be — the pointer preceded every\n * call the child ever made, which makes the child's FIRST tool call evidence\n * rather than the row after the anchor. {@link gradeRelayed} judges from there,\n * inclusively, while {@link gradeInjection} keeps its exclusive `anchor + 1`.\n *\n * A relayed row also has no injected text on disk to take spans from — the arm\n * renders a title, a price and possibly a fetched body, and stores none of it —\n * so its span evidence comes from the piece's TITLE alone, which is usually no\n * spans at all. Relayed findings are therefore judged almost entirely on the\n * strong evidence (an explicit read, or the url), which is the right way round.\n * Storing the injected text is a second schema change and is not this one.\n *\n * The functions here are pure over parsed rows, except the two that touch the\n * filesystem at the bottom; the command in commands/grade.ts owns the store.\n */\n\n/** How many tool calls after the anchor a copied span may still be evidence. */\nexport const SPAN_WINDOW = 10;\n\n/** A transcript nothing has appended to for this long belongs to a session that\n * is over, whether or not a Stop hook ever stamped `ended_at` (a crashed or\n * killed harness never does). */\nexport const ENDED_AFTER_MS = 30 * 60_000;\n\n/** How many tool inputs `--explain` shows for a rejected row, and how much of\n * each: enough to see what the agent did instead, not a transcript dump. */\nconst EVIDENCE_ROWS = 3;\nconst EVIDENCE_CHARS = 200;\n\n/** A session id is used as a filename, so it is checked like one. */\nconst SESSION_ID_RE = /^[A-Za-z0-9-]{1,80}$/;\n\n/**\n * An agent id becomes a filename too (`agent-<id>.jsonl`), so it gets the same\n * treatment as a session id.\n *\n * THE ONLY DEFINITION, and every other reader takes it from here rather than\n * restating it: `prelude` interpolates it into the rendered scripts, where\n * `identityOf` and the capture ask's flag splice both read that one declaration,\n * and `publish --agent` tests against this constant directly. The splice and\n * `--agent` used to share a wider `shell-safe` copy admitting `.` and `:` on the\n * reasoning that only shell metacharacters matter in a command line: `:` is the\n * separator `agentKey` joins on, so an id carrying one keys a child's rows into\n * another child's range, and an id one reader accepts and another refuses is a\n * row that can never be graded or reported.\n */\nexport const AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The only two row kinds that decide anything; see the module note. */\nexport interface TranscriptRow {\n /** 1-based line number in the JSONL, for `--explain`. */\n line: number;\n kind: 'context' | 'tool_use';\n text: string;\n}\n\nexport interface GradeTarget {\n resourceId: string | null;\n url: string | null;\n title: string | null;\n}\n\nexport type Verdict =\n | { outcome: 'used'; by: 'read' | 'span' | 'likely'; evidence: string }\n | { outcome: 'rejected'; by: 'none'; evidence: string[] }\n | { outcome: 'unobserved'; by: 'none' }\n /** Still open: the session may yet answer, so nothing is written. */\n | { outcome: null; evidence: string[] };\n\n/**\n * The transcript, reduced to the rows that can decide a verdict.\n *\n * A malformed line is skipped rather than failing the parse: a transcript being\n * appended to while this runs can end mid-line, and one truncated row is not a\n * reason to refuse to grade a session.\n *\n * `isCompactSummary` rows are dropped. A compaction REPLAYS earlier tool calls\n * into a summary the assistant then carries, so counting them would let one\n * injection be \"used\" by the echo of a call that happened before it was shown.\n */\nexport function parseTranscript(jsonl: string): TranscriptRow[] {\n const rows: TranscriptRow[] = [];\n const lines = jsonl.split('\\n');\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i];\n if (raw === undefined || raw.length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n continue;\n }\n if (!isRecord(parsed)) continue;\n const line = i + 1;\n const attachment = parsed.attachment;\n if (isRecord(attachment) && attachment.type === 'hook_additional_context') {\n rows.push({ line, kind: 'context', text: contextText(attachment.content) });\n continue;\n }\n if (parsed.type !== 'assistant' || parsed.isCompactSummary === true) continue;\n const message = parsed.message;\n if (!isRecord(message) || !Array.isArray(message.content)) continue;\n for (const block of message.content) {\n if (!isRecord(block) || block.type !== 'tool_use') continue;\n rows.push({ line, kind: 'tool_use', text: JSON.stringify(block.input ?? null) });\n }\n }\n return rows;\n}\n\n/**\n * Where the injection landed, as an index into `rows`, or -1.\n *\n * THE FIRST MATCH, not the nearest one after the row's timestamp. The\n * `injections_shown_once` index makes one injected row per (session,\n * resourceId), so there is only ever one context row naming a given piece, and\n * matching it by content beats matching it by clock: the hook's `at` and the\n * transcript's line order are written by different processes.\n *\n * Id, then url, then title, weakest last: a title is display text that could\n * appear in an unrelated context row, so it is what is tried when the piece has\n * nothing more specific to be found by.\n */\nexport function findAnchor(rows: TranscriptRow[], target: GradeTarget): number {\n for (const needle of [target.resourceId, target.url, target.title]) {\n if (needle === null || needle.length === 0) continue;\n const at = rows.findIndex((row) => row.kind === 'context' && row.text.includes(needle));\n if (at !== -1) return at;\n }\n return -1;\n}\n\n/**\n * The backtick spans in the injected text worth looking for later: at least two\n * whitespace-separated words, deduped.\n *\n * TWO WORDS IS THE FLOOR because one is noise. A note names `pnpm`, `useEffect`\n * or a filename, the agent types the same token in the next command, and a\n * one-word rule calls that reuse — on a machine where the agent was going to\n * type it anyway. Two words is a phrase somebody copied.\n */\nexport function backtickSpans(text: string): string[] {\n const spans = new Set<string>();\n for (const match of text.matchAll(/`([^`\\n]+)`/g)) {\n const span = (match[1] ?? '').trim();\n if (span.split(/\\s+/).filter((w) => w.length > 0).length >= 2) spans.add(span);\n }\n return [...spans];\n}\n\n/** A candidate token has to carry its own punctuation to qualify — see\n * {@link likelyTokens}. */\nconst LIKELY_TOKEN_RE = /\\b[A-Za-z][A-Za-z0-9]*(?:[:_./-][A-Za-z0-9]+)+\\b/g;\nconst LIKELY_MIN_CHARS = 4;\n/** Compounds common enough in ordinary prose to look like a command or a path\n * but never are one. Not a promise of completeness — the punctuation\n * requirement in {@link LIKELY_TOKEN_RE} is what does most of the work; this\n * catches the handful of hyphenated English words that would otherwise slip\n * through it. */\nconst LIKELY_GENERIC = new Set([\n 're-run',\n 're-runs',\n 're-ran',\n 're-executes',\n 're-executed',\n 'up-to-date',\n 'well-known',\n 'self-contained',\n 'read-only',\n 'long-lived',\n 'built-in',\n 'one-word',\n 'two-word',\n 'so-called',\n 'case-by-case',\n 'pre-commit',\n 'post-commit',\n 'e.g',\n 'i.e',\n // The injection's OWN scaffolding, not anything a seller wrote: PUBLIC_OPENER,\n // CLOSING_LINE and the body fence itself (`--- tenjin-body <nonce> ---`) from\n // hooks/prose.ts land in every full-form injection, so without these three\n // `likelyTokens(fullForm(...))` always nets its own boilerplate as a\n // candidate.\n 'third-party',\n 're-verifying',\n 'tenjin-body',\n]);\n\n/**\n * Command heads and file basenames named anywhere in `text`, with no backticks\n * at all — the weaker, single-token net {@link judge} tries below `span` for a\n * note that describes a command in prose instead of quoting it\n * (tenjin-agent#254b: \"gh run rerun\" named only in a title, \"pnpm check\" named\n * only as English words, each with a tool call that actually followed it).\n *\n * CONSERVATIVE ON PURPOSE. A bare English word (\"run\", \"check\", or \"pnpm\" on\n * its own) is exactly what the two-word floor on {@link backtickSpans} already\n * excludes as noise the agent was going to type anyway; a single-token net\n * that took bare words would reopen that hole wider than the floor closes it.\n * So a candidate must carry its own internal structure — a colon, dot, slash,\n * underscore or hyphen joining two word-shaped halves, the way a subcommand\n * (`db:generate`), a filename (`ci.yml`), or a path segment does — which a\n * plain English word essentially never does, and it must be at least\n * {@link LIKELY_MIN_CHARS} long.\n *\n * BACKTICK CONTENT IS STRIPPED FIRST, so a span already tried (and ranked\n * above this) is never re-offered as weaker evidence for the same text.\n *\n * THE PIECE'S OWN ID AND URL ARE EXCLUDED. Those already have a dedicated,\n * stronger `read` verdict; re-crediting them here would rank a followed\n * pointer BELOW a copied identifier instead of above it.\n */\nexport function likelyTokens(text: string, target: GradeTarget): string[] {\n const stripped = text.replace(/`[^`\\n]+`/g, ' ');\n const tokens = new Set<string>();\n for (const match of stripped.matchAll(LIKELY_TOKEN_RE)) {\n const token = match[0];\n if (token.length < LIKELY_MIN_CHARS) continue;\n if (LIKELY_GENERIC.has(token.toLowerCase())) continue;\n // A FRAGMENT counts as the id or the url, not just an exact match: a uuid\n // is all hyphens and hex, so the token regex can walk in from the middle\n // of one (`bbbb-cccc-dddd-...`) and still name nothing but the piece the\n // `read` tier already owns.\n if (target.resourceId !== null && target.resourceId.includes(token)) continue;\n if (target.url !== null && target.url.length > 0 && target.url.includes(token)) continue;\n tokens.add(token);\n }\n return [...tokens];\n}\n\n/**\n * The verdict for one injection, given its transcript and its anchor.\n *\n * Read beats span: both may be present, and \"the agent went and read the piece\"\n * is the stronger claim, so it is the one reported.\n */\nexport function gradeInjection(\n rows: TranscriptRow[],\n anchor: number,\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n if (anchor < 0 || anchor >= rows.length) return { outcome: 'unobserved', by: 'none' };\n // EXCLUSIVE: the anchor row IS the injection, so the calls that can answer for\n // it are the ones after it. The ones BEFORE it are what a span or a likely\n // token has to clear to earn credit — see the module note on #254a. Bounded\n // to the same SPAN_WINDOW as `after`: a session's first call from an hour\n // before the injection is not \"standing boilerplate\" any more than a session's\n // fiftieth call after it is still \"the injection in view\" — both are the same\n // claim, made symmetrically.\n const before = rows\n .slice(0, anchor)\n .filter((row) => row.kind === 'tool_use')\n .slice(-SPAN_WINDOW);\n const after = rows.slice(anchor + 1).filter((row) => row.kind === 'tool_use');\n const text = rows[anchor]?.text ?? '';\n return judge(after, before, backtickSpans(text), likelyTokens(text, target), target, opts.ended);\n}\n\n/**\n * Where a relayed finding's evidence starts: the first `tool_use` row, or -1.\n *\n * The caller reports it as the anchor line under `--explain`, so a verdict on a\n * child still names the row it was read from.\n */\nexport function firstToolCall(rows: TranscriptRow[]): number {\n return rows.findIndex((row) => row.kind === 'tool_use');\n}\n\n/**\n * The verdict for a finding RELAYED to a subagent, given that child's own\n * transcript.\n *\n * INCLUSIVE OF THE FIRST CALL, and with no anchor at all — see the module note.\n * A child that made no tool calls has done nothing that could be evidence, so it\n * is `rejected` once it is over and open while it runs, exactly as an\n * unanswered main-session row is.\n */\nexport function gradeRelayed(\n rows: TranscriptRow[],\n target: GradeTarget,\n opts: { ended: boolean },\n): Verdict {\n const calls = rows.filter((row) => row.kind === 'tool_use');\n // The title is the only injected text this row left on disk; usually it holds\n // no two-word backtick span at all, and that is the documented limit of what\n // a relayed row can be judged `span` or `likely` on. No pre-injection\n // exclusion here: the pointer preceded the child's first call, so there is no\n // \"before\" inside this transcript for anything to have leaked from.\n const title = target.title ?? '';\n return judge(calls, [], backtickSpans(title), likelyTokens(title, target), target, opts.ended);\n}\n\n/**\n * The evidence rules themselves, over whichever tool calls the caller decided\n * are eligible. Shared byte-for-byte by both verdict functions, so a relayed row\n * and a main-session row can never drift into being judged by different rules.\n *\n * Read beats span beats likely: each may be present alongside a weaker one, and\n * the strongest claim actually supported is the one reported.\n *\n * `before` is up to {@link SPAN_WINDOW} tool calls that happened in this same\n * session BEFORE the injection (empty for a relayed row, which has none). A\n * span or a likely token already present there is boilerplate the session was\n * going to write anyway, so it earns no credit here — tenjin-agent#254a.\n */\nfunction judge(\n after: TranscriptRow[],\n before: TranscriptRow[],\n spans: string[],\n likely: string[],\n target: GradeTarget,\n ended: boolean,\n): Verdict {\n const readRe = target.resourceId === null ? null : readCommandRe(target.resourceId);\n for (const row of after) {\n if (readRe !== null && readRe.test(row.text)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n if (target.url !== null && target.url.length > 0 && row.text.includes(target.url)) {\n return { outcome: 'used', by: 'read', evidence: cap(row.text) };\n }\n }\n // A TOKEN BOUNDARY MATCH, not a substring, ON BOTH SIDES: `db:generate` is a\n // plain substring of `db:generate-types`, so a pre-injection call to the\n // latter must not erase credit for a genuine post-injection call to the\n // former (the `before` side) — but by the same logic, a post-injection call\n // to `db:generate-types` must not be credited as a hit for a note that only\n // ever named `db:generate` (the `after` side): that is the identical\n // boilerplate #254a exists to exclude, just spelled with the shorter token\n // as the candidate instead of the longer one. Plain `includes` on one side\n // and a boundary match on the other opens exactly that gap — fixed by\n // sharing one boundary test both directions (tenjin-agent#276 review round\n // 2, major). The class in the lookaround is exactly {@link\n // LIKELY_TOKEN_RE}'s own — a colon, dot, slash, underscore or hyphen still\n // extends a token, so this only rules out landing inside a longer one, not\n // a real reappearance next to punctuation.\n const atBoundary = (haystack: string, candidate: string): boolean =>\n new RegExp(`(?<![A-Za-z0-9:_./-])${escapeRe(candidate)}(?![A-Za-z0-9:_./-])`).test(haystack);\n const seenBefore = (candidate: string): boolean =>\n before.some((row) => atBoundary(row.text, candidate));\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = spans.find((span) => !seenBefore(span) && atBoundary(row.text, span));\n // Capped like every other evidence string here: the span is copied out of\n // injected text, which came off a shelf, and `--explain` prints it.\n if (hit !== undefined) return { outcome: 'used', by: 'span', evidence: cap(hit) };\n }\n for (const row of after.slice(0, SPAN_WINDOW)) {\n const hit = likely.find((token) => !seenBefore(token) && atBoundary(row.text, token));\n if (hit !== undefined) return { outcome: 'used', by: 'likely', evidence: cap(hit) };\n }\n const evidence = after.slice(0, EVIDENCE_ROWS).map(cap);\n return ended ? { outcome: 'rejected', by: 'none', evidence } : { outcome: null, evidence };\n}\n\n/** `7d`, `24h`, `30m` as milliseconds. Anything else is a usage error rather\n * than a silent default, so a typo cannot quietly widen or narrow a sweep. */\nexport function parseSince(text: string): number {\n const match = /^(\\d+)([dhm])$/.exec(text.trim());\n const value = match === null ? 0 : Number(match[1]);\n if (match === null || value <= 0) {\n throw new CliError('USAGE', `Invalid --since window: ${JSON.stringify(text)}`, {\n fix: 'Pass a window like 7d, 24h or 30m.',\n });\n }\n const unit = { d: 24 * 60 * 60_000, h: 60 * 60_000, m: 60_000 }[match[2] as 'd' | 'h' | 'm'];\n return value * unit;\n}\n\n/**\n * Where a session's transcript is, or WHY there is none.\n *\n * `absent` is a FACT ABOUT THE SESSION: the projects directory was listed and\n * holds no file for it. `unreadable` is a fact about this machine right now —\n * no projects directory, a home that is not mounted, a permissions change\n * mid-run — and says nothing about the session at all.\n */\nexport type TranscriptLookup =\n { kind: 'found'; path: string } | { kind: 'absent' } | { kind: 'unreadable'; reason: string };\n\n/**\n * The transcript for a session, or for one subagent of it, or why it was not\n * found.\n *\n * BY READDIR, not by mangling the cwd into a directory name. Claude Code names\n * the project directory from the working directory with a substitution this CLI\n * would have to reimplement and keep in step (and which a worktree, a symlinked\n * home or a renamed checkout each break differently); the session id is a uuid\n * and is unique across them, so one listing finds it wherever it landed.\n *\n * WITH AN AGENT ID IT IS A DIFFERENT FILE, not a different search: a subagent\n * writes to `<session>/subagents/agent-<id>.jsonl` beside the parent's\n * `<session>.jsonl`, under the same project directory. The child's tool calls\n * appear in NO parent file, so a row stamped with an agent id is answered only\n * here.\n *\n * THE TWO NEGATIVE ANSWERS ARE NOT THE SAME ANSWER, and collapsing them to\n * `null` is how a transient fault becomes permanent: the caller turns \"no\n * transcript\" into `unobserved`, `unobserved` is a verdict, and a verdict is\n * never re-graded. One run under a home directory that could not be read would\n * have closed every open row on the machine as never-seen, with no way back.\n */\nexport async function findTranscript(\n homeDir: string,\n sessionId: string,\n agentId: string | null = null,\n): Promise<TranscriptLookup> {\n // An id that cannot be a filename names no transcript in any project\n // directory, now or ever: that is absence, and it is permanent.\n if (!SESSION_ID_RE.test(sessionId)) return { kind: 'absent' };\n if (agentId !== null && !AGENT_ID_RE.test(agentId)) return { kind: 'absent' };\n const { readdir, stat } = await import('node:fs/promises');\n const { join } = await import('node:path');\n const projects = join(homeDir, '.claude', 'projects');\n let dirs: string[];\n try {\n dirs = (await readdir(projects, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch (err) {\n // A missing projects directory included: a machine where the harness has\n // never run, or has not run yet, has not told us anything about this row.\n return { kind: 'unreadable', reason: errorReason(err) };\n }\n let blocked: string | null = null;\n for (const dir of dirs) {\n const path =\n agentId === null\n ? join(projects, dir, `${sessionId}.jsonl`)\n : join(projects, dir, sessionId, 'subagents', `agent-${agentId}.jsonl`);\n try {\n if ((await stat(path)).isFile()) return { kind: 'found', path };\n } catch (err) {\n // ENOENT is the ordinary answer — the session is simply not in THIS\n // project directory, and on the child path its `<session>/` directory may\n // not exist at all (ENOENT, or ENOTDIR where a plain file sits where the\n // directory would be). Anything else is a directory that could be hiding\n // it, so the sweep can no longer claim the file is absent.\n const code = errorCode(err);\n if (code !== 'ENOENT' && code !== 'ENOTDIR') blocked ??= errorReason(err);\n }\n }\n return blocked === null ? { kind: 'absent' } : { kind: 'unreadable', reason: blocked };\n}\n\n/** Has nothing been appended to this transcript for {@link ENDED_AFTER_MS}? The\n * half of \"the session is over\" that survives a harness which never stopped\n * cleanly and so never stamped `ended_at`. Unreadable reads as NOT idle: an\n * unknown must never manufacture a `rejected`. */\nexport async function transcriptIdle(path: string, nowMs: number): Promise<boolean> {\n try {\n const { stat } = await import('node:fs/promises');\n return nowMs - (await stat(path)).mtimeMs > ENDED_AFTER_MS;\n } catch {\n return false;\n }\n}\n\n/** An errno if the platform gave one, else the message: short enough to print\n * on the one `--explain` line that says why a row was left alone. Exported so\n * the caller's own read of the file it was handed reports failures in the same\n * words this one does. */\nexport function errorReason(err: unknown): string {\n const code = errorCode(err);\n if (code !== null) return code;\n return cap(err instanceof Error ? err.message : 'unknown error');\n}\n\nfunction errorCode(err: unknown): string | null {\n return isRecord(err) && typeof err.code === 'string' ? err.code : null;\n}\n\nfunction readCommandRe(resourceId: string): RegExp {\n return new RegExp(`tenjin\\\\s+(?:read|inspect)\\\\s+${escapeRe(resourceId)}`);\n}\n\nfunction escapeRe(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction cap(row: TranscriptRow | string): string {\n const text = typeof row === 'string' ? row : row.text;\n return text.length > EVIDENCE_CHARS ? `${text.slice(0, EVIDENCE_CHARS)}…` : text;\n}\n\n/**\n * The injected text, whatever shape the attachment carried it in: a bare string,\n * an array of strings, or an array of `{ type: 'text', text }` blocks. All three\n * appear, and the anchor match only needs the words.\n */\nfunction contextText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n const parts: string[] = [];\n for (const item of content) {\n if (typeof item === 'string') parts.push(item);\n else if (isRecord(item) && typeof item.text === 'string') parts.push(item.text);\n }\n return parts.join('\\n');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;AA+EO,IAAM,iBAAiB,KAAK;AAwB5B,IAAM,cAAc;","names":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/lib/production-origin.ts
|
|
4
|
+
var PRODUCTION_ORIGIN = "https://tenjin.sh";
|
|
5
|
+
var PRODUCTION_HOST = new URL(PRODUCTION_ORIGIN).host;
|
|
6
|
+
var KNOWN_DEPLOYMENT_ORIGINS = /* @__PURE__ */ new Set([
|
|
7
|
+
PRODUCTION_ORIGIN,
|
|
8
|
+
"https://tenjin.blog"
|
|
9
|
+
]);
|
|
10
|
+
function isSameDeployment(a, b) {
|
|
11
|
+
if (a === b) return true;
|
|
12
|
+
return KNOWN_DEPLOYMENT_ORIGINS.has(a) && KNOWN_DEPLOYMENT_ORIGINS.has(b);
|
|
13
|
+
}
|
|
14
|
+
function knownDeploymentOrigins() {
|
|
15
|
+
return [...KNOWN_DEPLOYMENT_ORIGINS];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
PRODUCTION_ORIGIN,
|
|
20
|
+
isSameDeployment,
|
|
21
|
+
knownDeploymentOrigins
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=chunk-XQJXNMSB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/production-origin.ts"],"sourcesContent":["/**\n * The one place the production Tenjin origin is written down. Every shipped\n * default, fallback, identity string, and piece of operator copy that names the\n * live site derives from here; `production-origin.test.ts` keeps it that way.\n *\n * This is NOT the base URL a command talks to. Ordinary requests resolve\n * `baseUrl` through config/flag/env precedence (`CONFIG_DEFAULTS.baseUrl` merely\n * starts from this value); `fund` alone pins production with no override surface\n * at all (owner decision, 2026-08-12) because its mint signs with the wallet key.\n * `fund.test.ts` and `client-meta.test.ts` each hold their own written-out copy,\n * so flipping this line alone reds the suite instead of moving the money path.\n */\nexport const PRODUCTION_ORIGIN = 'https://tenjin.sh';\n\n/**\n * The bare host, for prose and messages that name the site rather than link to\n * it. Derived, not written twice: a flip cannot leave the two disagreeing.\n */\nexport const PRODUCTION_HOST = new URL(PRODUCTION_ORIGIN).host;\n\n/**\n * Every origin the ONE production deployment answers on, as `URL.origin` spells\n * it. Membership means a request to any of them reaches the same server,\n * publishers, prices, and SIWX domain acceptance. It exists because the server\n * builds candidate URLs from its own `NEXT_PUBLIC_APP_URL`, not the request\n * host, so the moment tenjin#402 flips that global a CLI on the other origin\n * sees every candidate as off-origin (tenjin#738).\n *\n * Membership is NOT trust and NOT an allowlist of places the CLI may pay, but it\n * IS the widest set a wallet-signed credential can reach, so widening it is a\n * security change. Removal runbook: docs/safety-model.md.\n */\nconst KNOWN_DEPLOYMENT_ORIGINS: ReadonlySet<string> = new Set([\n PRODUCTION_ORIGIN,\n 'https://tenjin.blog',\n]);\n\n/**\n * Do these two origins name the same deployment? Exact match, or two members of\n * the set. BOTH sides must be members, so a self-hosted or preview base gains no\n * alias and keeps today's strict compare, and a differing scheme or port is a\n * different origin that aliases to nothing. Takes `URL.origin` strings; anything\n * else is not a member and falls through to the exact compare.\n */\nexport function isSameDeployment(a: string, b: string): boolean {\n if (a === b) return true;\n return KNOWN_DEPLOYMENT_ORIGINS.has(a) && KNOWN_DEPLOYMENT_ORIGINS.has(b);\n}\n\n/** The set as a plain array, for the generated hook script that cannot import. */\nexport function knownDeploymentOrigins(): string[] {\n return [...KNOWN_DEPLOYMENT_ORIGINS];\n}\n"],"mappings":";;;AAYO,IAAM,oBAAoB;AAM1B,IAAM,kBAAkB,IAAI,IAAI,iBAAiB,EAAE;AAc1D,IAAM,2BAAgD,oBAAI,IAAI;AAAA,EAC5D;AAAA,EACA;AACF,CAAC;AASM,SAAS,iBAAiB,GAAW,GAAoB;AAC9D,MAAI,MAAM,EAAG,QAAO;AACpB,SAAO,yBAAyB,IAAI,CAAC,KAAK,yBAAyB,IAAI,CAAC;AAC1E;AAGO,SAAS,yBAAmC;AACjD,SAAO,CAAC,GAAG,wBAAwB;AACrC;","names":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
keccak_256
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KG3D7FIF.js";
|
|
5
5
|
import {
|
|
6
6
|
bytesToHex
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-BPMWXTFX.js";
|
|
8
8
|
import {
|
|
9
9
|
__commonJS,
|
|
10
10
|
__require,
|
|
@@ -7803,4 +7803,4 @@ export {
|
|
|
7803
7803
|
p2 as p,
|
|
7804
7804
|
m2 as m
|
|
7805
7805
|
};
|
|
7806
|
-
//# sourceMappingURL=chunk-
|
|
7806
|
+
//# sourceMappingURL=chunk-XZKD7DIF.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
CliError
|
|
4
|
+
} from "./chunk-3UCIG4TG.js";
|
|
5
|
+
|
|
6
|
+
// src/lib/ids.ts
|
|
7
|
+
var ATOMIC_RE = /^\d{1,39}$/;
|
|
8
|
+
|
|
9
|
+
// src/lib/money.ts
|
|
10
|
+
var USDC_DECIMALS = 6;
|
|
11
|
+
function parseUsdToAtomic(input) {
|
|
12
|
+
const trimmed = input.trim();
|
|
13
|
+
if (!/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
14
|
+
throw new CliError("USAGE", `Invalid USD amount: ${JSON.stringify(input)}`, {
|
|
15
|
+
fix: "Pass a non-negative decimal like 0.25 or 5."
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
const [whole, frac = ""] = trimmed.split(".");
|
|
19
|
+
if (frac.length > USDC_DECIMALS) {
|
|
20
|
+
throw new CliError(
|
|
21
|
+
"USAGE",
|
|
22
|
+
`USD amount ${JSON.stringify(input)} has more than 6 decimal places`,
|
|
23
|
+
{
|
|
24
|
+
fix: "USDC supports at most 6 decimal places (micro-dollars)."
|
|
25
|
+
}
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, "0")}`);
|
|
29
|
+
return atomic.toString();
|
|
30
|
+
}
|
|
31
|
+
function atomicToUsd(atomic) {
|
|
32
|
+
const trimmed = atomic.trim();
|
|
33
|
+
if (!/^\d+$/.test(trimmed)) {
|
|
34
|
+
throw new CliError("INTERNAL", `Malformed atomic amount: ${JSON.stringify(atomic)}`);
|
|
35
|
+
}
|
|
36
|
+
const value = BigInt(trimmed);
|
|
37
|
+
const base = 10n ** BigInt(USDC_DECIMALS);
|
|
38
|
+
const whole = value / base;
|
|
39
|
+
const frac = (value % base).toString().padStart(USDC_DECIMALS, "0").replace(/0+$/, "");
|
|
40
|
+
return frac.length > 0 ? `${whole}.${frac}` : whole.toString();
|
|
41
|
+
}
|
|
42
|
+
function toMoney(atomic) {
|
|
43
|
+
return { atomic, usd: atomicToUsd(atomic) };
|
|
44
|
+
}
|
|
45
|
+
function formatUsdDisplay(atomic) {
|
|
46
|
+
const [whole, frac = ""] = atomicToUsd(atomic).split(".");
|
|
47
|
+
return `${whole}.${frac.padEnd(2, "0")}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export {
|
|
51
|
+
ATOMIC_RE,
|
|
52
|
+
parseUsdToAtomic,
|
|
53
|
+
toMoney,
|
|
54
|
+
formatUsdDisplay
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=chunk-Y527D4TV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/ids.ts","../src/lib/money.ts"],"sourcesContent":["/**\n * The shared identity patterns for server-controlled values that become file\n * paths, URL segments, or terminal output. One definition so a future change\n * (e.g. accepting uppercase ids) cannot be applied in one command and missed in\n * another. SLUG_RE must match the server's slugify charset (lib/posts.ts:\n * lowercase a-z0-9 groups joined by single hyphens, no leading/trailing hyphen).\n */\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n/** A non-negative atomic USDC integer string (6-decimal base units). */\nexport const ATOMIC_RE = /^\\d{1,39}$/;\n","import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n"],"mappings":";;;;;;AAUO,IAAM,YAAY;;;ACLzB,IAAM,gBAAgB;AAQf,SAAS,iBAAiB,OAAuB;AACtD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,gBAAgB,KAAK,OAAO,GAAG;AAClC,UAAM,IAAI,SAAS,SAAS,uBAAuB,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,MAC1E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,QAAQ,MAAM,GAAG;AAC5C,MAAI,KAAK,SAAS,eAAe;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,cAAc,KAAK,UAAU,KAAK,CAAC;AAAA,MACnC;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,OAAO,GAAG,KAAK,GAAG,KAAK,OAAO,eAAe,GAAG,CAAC,EAAE;AAClE,SAAO,OAAO,SAAS;AACzB;AAQO,SAAS,YAAY,QAAwB;AAClD,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI,CAAC,QAAQ,KAAK,OAAO,GAAG;AAC1B,UAAM,IAAI,SAAS,YAAY,4BAA4B,KAAK,UAAU,MAAM,CAAC,EAAE;AAAA,EACrF;AACA,QAAM,QAAQ,OAAO,OAAO;AAC5B,QAAM,OAAO,OAAO,OAAO,aAAa;AACxC,QAAM,QAAQ,QAAQ;AACtB,QAAM,QAAQ,QAAQ,MAAM,SAAS,EAAE,SAAS,eAAe,GAAG,EAAE,QAAQ,OAAO,EAAE;AACrF,SAAO,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS;AAC/D;AAyBO,SAAS,QAAQ,QAAuB;AAC7C,SAAO,EAAE,QAAQ,KAAK,YAAY,MAAM,EAAE;AAC5C;AAQO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,YAAY,MAAM,EAAE,MAAM,GAAG;AACxD,SAAO,GAAG,KAAK,IAAI,KAAK,OAAO,GAAG,GAAG,CAAC;AACxC;","names":[]}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
findAllProjectFiles,
|
|
4
|
+
findNearestProjectFiles,
|
|
5
|
+
mainWorktreeOf,
|
|
6
|
+
ownedCandidates,
|
|
7
|
+
projectRoot
|
|
8
|
+
} from "./chunk-7WU4OPLP.js";
|
|
9
|
+
import {
|
|
10
|
+
CONFIG_DEFAULTS,
|
|
11
|
+
loadRawConfig,
|
|
12
|
+
parseRouterLayer
|
|
13
|
+
} from "./chunk-YVFXE7RR.js";
|
|
14
|
+
import {
|
|
15
|
+
CliError
|
|
16
|
+
} from "./chunk-3UCIG4TG.js";
|
|
17
|
+
import {
|
|
18
|
+
configPath
|
|
19
|
+
} from "./chunk-SJLTEINJ.js";
|
|
20
|
+
|
|
21
|
+
// src/router/settings.ts
|
|
22
|
+
import { readFile } from "node:fs/promises";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join, resolve } from "node:path";
|
|
25
|
+
var PROJECT_ROUTER_FILE = join(".tenjin", "config.json");
|
|
26
|
+
var LOCAL_ROUTER_FILE = join(".tenjin", "config.local.json");
|
|
27
|
+
async function routerSettings(input, deps = {}) {
|
|
28
|
+
const globalPath = configPath(input.dataDir);
|
|
29
|
+
const global = (input.config ?? await loadRawConfig(input.dataDir)).router;
|
|
30
|
+
let enabled = {
|
|
31
|
+
value: CONFIG_DEFAULTS.router.enabled,
|
|
32
|
+
source: "default"
|
|
33
|
+
};
|
|
34
|
+
let context = {
|
|
35
|
+
value: CONFIG_DEFAULTS.router.context,
|
|
36
|
+
source: "default"
|
|
37
|
+
};
|
|
38
|
+
if (global?.enabled !== void 0) {
|
|
39
|
+
enabled = { value: global.enabled, source: "file", path: globalPath };
|
|
40
|
+
}
|
|
41
|
+
if (global?.context !== void 0) {
|
|
42
|
+
context = { value: global.context, source: "file", path: globalPath };
|
|
43
|
+
}
|
|
44
|
+
for (const { source, path, layer } of await projectLayers(input, deps)) {
|
|
45
|
+
if (layer.enabled !== void 0 && (layer.enabled === false || enabled.value)) {
|
|
46
|
+
enabled = { value: layer.enabled, source, path };
|
|
47
|
+
}
|
|
48
|
+
if (layer.context !== void 0 && (layer.context === "turn" || context.value === "session")) {
|
|
49
|
+
context = { value: layer.context, source, path };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { enabled, context };
|
|
53
|
+
}
|
|
54
|
+
var ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];
|
|
55
|
+
async function projectLayers(input, deps) {
|
|
56
|
+
const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {
|
|
57
|
+
...deps,
|
|
58
|
+
// $HOME/.tenjin is the global scope, not a project.
|
|
59
|
+
homeIsProject: false
|
|
60
|
+
});
|
|
61
|
+
const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);
|
|
62
|
+
const outer = main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];
|
|
63
|
+
const layers = [];
|
|
64
|
+
for (const { dir, found } of [...outer, ...levels.reverse()]) {
|
|
65
|
+
if (resolve(dir, ".tenjin") === resolve(input.dataDir)) continue;
|
|
66
|
+
for (const path of found) {
|
|
67
|
+
const file = await readProjectRouterFile(path);
|
|
68
|
+
if (file === null) continue;
|
|
69
|
+
layers.push({
|
|
70
|
+
source: path === join(dir, LOCAL_ROUTER_FILE) ? "local" : "project",
|
|
71
|
+
path,
|
|
72
|
+
layer: file.layer
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return layers;
|
|
77
|
+
}
|
|
78
|
+
var ABSENT = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
|
|
79
|
+
async function readProjectRouterFile(path) {
|
|
80
|
+
let raw;
|
|
81
|
+
try {
|
|
82
|
+
raw = await readFile(path, "utf8");
|
|
83
|
+
} catch (err) {
|
|
84
|
+
if (ABSENT.has(String(err.code))) return null;
|
|
85
|
+
throw invalid(path, "could not be read", err);
|
|
86
|
+
}
|
|
87
|
+
let json;
|
|
88
|
+
try {
|
|
89
|
+
json = JSON.parse(raw);
|
|
90
|
+
} catch (err) {
|
|
91
|
+
throw invalid(path, "is not valid JSON", err);
|
|
92
|
+
}
|
|
93
|
+
const layer = parseRouterLayer(json, path);
|
|
94
|
+
return { json, layer };
|
|
95
|
+
}
|
|
96
|
+
async function projectRouterPath(input, deps = {}) {
|
|
97
|
+
const home = deps.homeDir ?? homedir();
|
|
98
|
+
const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {
|
|
99
|
+
...deps,
|
|
100
|
+
warn: () => void 0,
|
|
101
|
+
homeIsProject: false
|
|
102
|
+
});
|
|
103
|
+
const dir = hit?.dir ?? await projectRoot(input.cwd, home);
|
|
104
|
+
if (dir === home) {
|
|
105
|
+
throw new CliError(
|
|
106
|
+
"USAGE",
|
|
107
|
+
"Your home directory is not a project: its .tenjin is the global config.",
|
|
108
|
+
{
|
|
109
|
+
fix: "Run it from inside the project, or drop --project to set it for this machine."
|
|
110
|
+
}
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);
|
|
114
|
+
}
|
|
115
|
+
function invalid(path, what, cause) {
|
|
116
|
+
return new CliError("CONFIG_INVALID", `Config at ${path} ${what}`, {
|
|
117
|
+
fix: `Fix ${path}, or delete it.`,
|
|
118
|
+
...cause !== void 0 ? { cause } : {}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export {
|
|
123
|
+
routerSettings,
|
|
124
|
+
readProjectRouterFile,
|
|
125
|
+
projectRouterPath
|
|
126
|
+
};
|
|
127
|
+
//# sourceMappingURL=chunk-YFPY4ONH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/settings.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n parseRouterLayer,\n type PartialConfig,\n type RouterContext,\n type RouterLayer,\n} from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { configPath } from '../lib/paths';\nimport {\n findAllProjectFiles,\n findNearestProjectFiles,\n mainWorktreeOf,\n ownedCandidates,\n projectRoot,\n type ProjectWalkDeps,\n} from '../lib/settings';\n\n/**\n * THE ONE READER OF THE ROUTER'S OWN KEYS, `router.enabled` and\n * `router.context`. Both hooks, the `request` tool, doctor, the status line and\n * `tenjin config` call {@link routerSettings} first, and nothing reads a router\n * key any other way.\n *\n * THE LAYERS: the default, `~/.tenjin/config.json`, then EVERY\n * `.tenjin/config.json` and `config.local.json` from the working directory up\n * to the git root, and in a linked git worktree the main checkout's pair too.\n * No environment variable.\n *\n * EVERY LAYER IS A FLOOR. `enabled` is false when any layer says false, and\n * `context` is `turn` when any layer says turn; a key a file leaves out\n * inherits, and a looser value is not read. So a file a cloned repository\n * carries cannot undo `tenjin config set router.enabled false` on this\n * machine, a package in a monorepo cannot undo its root, and a\n * `config.local.json` a repository commits anyway cannot undo the committed\n * one. Both keys fail toward less data sent, and no project file has a spend\n * key to loosen. The source reported is the nearest layer at the value.\n *\n * ONE PARSER. The global block is the one `loadRawConfig` already validated,\n * and a project file goes through `parseRouterLayer` from the same schema.\n */\n\n/** The committed project file and the personal one beside it. */\nexport const PROJECT_ROUTER_FILE = join('.tenjin', 'config.json');\nexport const LOCAL_ROUTER_FILE = join('.tenjin', 'config.local.json');\n\nexport type RouterSource = 'default' | 'file' | 'project' | 'local';\n\nexport interface RouterSetting<T> {\n value: T;\n source: RouterSource;\n /** The file that set it; absent for the default. */\n path?: string;\n}\n\nexport interface RouterSettings {\n enabled: RouterSetting<boolean>;\n context: RouterSetting<RouterContext>;\n}\n\nexport interface RouterSettingsInput {\n /** The directory the harness is working in. */\n cwd: string;\n /** The data dir whose `config.json` is the global layer. */\n dataDir: string;\n /** That file, when the caller has already loaded it; read here otherwise. */\n config?: PartialConfig;\n}\n\nexport async function routerSettings(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps = {},\n): Promise<RouterSettings> {\n const globalPath = configPath(input.dataDir);\n const global = (input.config ?? (await loadRawConfig(input.dataDir))).router;\n let enabled: RouterSetting<boolean> = {\n value: CONFIG_DEFAULTS.router.enabled,\n source: 'default',\n };\n let context: RouterSetting<RouterContext> = {\n value: CONFIG_DEFAULTS.router.context,\n source: 'default',\n };\n if (global?.enabled !== undefined) {\n enabled = { value: global.enabled, source: 'file', path: globalPath };\n }\n if (global?.context !== undefined) {\n context = { value: global.context, source: 'file', path: globalPath };\n }\n\n for (const { source, path, layer } of await projectLayers(input, deps)) {\n // Every layer is a floor: a value looser than the one so far is not read.\n if (layer.enabled !== undefined && (layer.enabled === false || enabled.value)) {\n enabled = { value: layer.enabled, source, path };\n }\n if (layer.context !== undefined && (layer.context === 'turn' || context.value === 'session')) {\n context = { value: layer.context, source, path };\n }\n }\n return { enabled, context };\n}\n\nconst ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];\n\n/**\n * Every project layer, outermost first so the nearest one at a value is the\n * one reported: the main checkout's pair when this is a linked worktree, then\n * each directory from the git root down to `cwd`, its project file before its\n * personal one.\n */\nasync function projectLayers(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps,\n): Promise<{ source: 'project' | 'local'; path: string; layer: RouterLayer }[]> {\n const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {\n ...deps,\n // $HOME/.tenjin is the global scope, not a project.\n homeIsProject: false,\n });\n const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);\n const outer =\n main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];\n const layers = [];\n for (const { dir, found } of [...outer, ...levels.reverse()]) {\n // A data dir kept inside a project is the global file, already read.\n if (resolve(dir, '.tenjin') === resolve(input.dataDir)) continue;\n for (const path of found) {\n const file = await readProjectRouterFile(path);\n if (file === null) continue;\n layers.push({\n source: path === join(dir, LOCAL_ROUTER_FILE) ? ('local' as const) : ('project' as const),\n path,\n layer: file.layer,\n });\n }\n }\n return layers;\n}\n\nconst ABSENT = new Set(['ENOENT', 'ENOTDIR']);\n\n/**\n * One project file: its whole JSON, for a writer that keeps sibling keys, and\n * its router layer through the one parser. Null when there is no file.\n */\nexport async function readProjectRouterFile(\n path: string,\n): Promise<{ json: Record<string, unknown>; layer: RouterLayer } | null> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (ABSENT.has(String((err as { code?: unknown }).code))) return null;\n throw invalid(path, 'could not be read', err);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw invalid(path, 'is not valid JSON', err);\n }\n const layer = parseRouterLayer(json, path);\n return { json: json as Record<string, unknown>, layer };\n}\n\n/**\n * Where `tenjin config set --project [--local]` writes from `cwd`: beside the\n * layer {@link routerSettings} already reads there, else at the git root, else\n * in `cwd`. Never in $HOME, whose `.tenjin/config.json` is the global file.\n */\nexport async function projectRouterPath(\n input: { cwd: string; local: boolean },\n deps: ProjectWalkDeps = {},\n): Promise<string> {\n const home = deps.homeDir ?? homedir();\n const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {\n ...deps,\n warn: () => undefined,\n homeIsProject: false,\n });\n const dir = hit?.dir ?? (await projectRoot(input.cwd, home));\n if (dir === home) {\n throw new CliError(\n 'USAGE',\n 'Your home directory is not a project: its .tenjin is the global config.',\n {\n fix: 'Run it from inside the project, or drop --project to set it for this machine.',\n },\n );\n }\n return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);\n}\n\nfunction invalid(path: string, what: string, cause?: unknown): CliError {\n return new CliError('CONFIG_INVALID', `Config at ${path} ${what}`, {\n fix: `Fix ${path}, or delete it.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AA6CvB,IAAM,sBAAsB,KAAK,WAAW,aAAa;AACzD,IAAM,oBAAoB,KAAK,WAAW,mBAAmB;AAyBpE,eAAsB,eACpB,OACA,OAAwB,CAAC,GACA;AACzB,QAAM,aAAa,WAAW,MAAM,OAAO;AAC3C,QAAM,UAAU,MAAM,UAAW,MAAM,cAAc,MAAM,OAAO,GAAI;AACtE,MAAI,UAAkC;AAAA,IACpC,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,UAAwC;AAAA,IAC1C,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AAEA,aAAW,EAAE,QAAQ,MAAM,MAAM,KAAK,MAAM,cAAc,OAAO,IAAI,GAAG;AAEtE,QAAI,MAAM,YAAY,WAAc,MAAM,YAAY,SAAS,QAAQ,QAAQ;AAC7E,gBAAU,EAAE,OAAO,MAAM,SAAS,QAAQ,KAAK;AAAA,IACjD;AACA,QAAI,MAAM,YAAY,WAAc,MAAM,YAAY,UAAU,QAAQ,UAAU,YAAY;AAC5F,gBAAU,EAAE,OAAO,MAAM,SAAS,QAAQ,KAAK;AAAA,IACjD;AAAA,EACF;AACA,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAEA,IAAM,eAAe,CAAC,qBAAqB,iBAAiB;AAQ5D,eAAe,cACb,OACA,MAC8E;AAC9E,QAAM,EAAE,QAAQ,QAAQ,IAAI,MAAM,oBAAoB,MAAM,KAAK,cAAc;AAAA,IAC7E,GAAG;AAAA;AAAA,IAEH,eAAe;AAAA,EACjB,CAAC;AACD,QAAM,OAAO,YAAY,OAAO,OAAO,MAAM,eAAe,SAAS,KAAK,OAAO;AACjF,QAAM,QACJ,SAAS,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,MAAM,OAAO,MAAM,gBAAgB,MAAM,cAAc,IAAI,EAAE,CAAC;AAC7F,QAAM,SAAS,CAAC;AAChB,aAAW,EAAE,KAAK,MAAM,KAAK,CAAC,GAAG,OAAO,GAAG,OAAO,QAAQ,CAAC,GAAG;AAE5D,QAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,MAAM,OAAO,EAAG;AACxD,eAAW,QAAQ,OAAO;AACxB,YAAM,OAAO,MAAM,sBAAsB,IAAI;AAC7C,UAAI,SAAS,KAAM;AACnB,aAAO,KAAK;AAAA,QACV,QAAQ,SAAS,KAAK,KAAK,iBAAiB,IAAK,UAAqB;AAAA,QACtE;AAAA,QACA,OAAO,KAAK;AAAA,MACd,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAM,SAAS,oBAAI,IAAI,CAAC,UAAU,SAAS,CAAC;AAM5C,eAAsB,sBACpB,MACuE;AACvE,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,MAAM,MAAM;AAAA,EACnC,SAAS,KAAK;AACZ,QAAI,OAAO,IAAI,OAAQ,IAA2B,IAAI,CAAC,EAAG,QAAO;AACjE,UAAM,QAAQ,MAAM,qBAAqB,GAAG;AAAA,EAC9C;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,SAAS,KAAK;AACZ,UAAM,QAAQ,MAAM,qBAAqB,GAAG;AAAA,EAC9C;AACA,QAAM,QAAQ,iBAAiB,MAAM,IAAI;AACzC,SAAO,EAAE,MAAuC,MAAM;AACxD;AAOA,eAAsB,kBACpB,OACA,OAAwB,CAAC,GACR;AACjB,QAAM,OAAO,KAAK,WAAW,QAAQ;AACrC,QAAM,MAAM,MAAM,wBAAwB,MAAM,KAAK,CAAC,qBAAqB,iBAAiB,GAAG;AAAA,IAC7F,GAAG;AAAA,IACH,MAAM,MAAM;AAAA,IACZ,eAAe;AAAA,EACjB,CAAC;AACD,QAAM,MAAM,KAAK,OAAQ,MAAM,YAAY,MAAM,KAAK,IAAI;AAC1D,MAAI,QAAQ,MAAM;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,SAAO,KAAK,KAAK,MAAM,QAAQ,oBAAoB,mBAAmB;AACxE;AAEA,SAAS,QAAQ,MAAc,MAAc,OAA2B;AACtE,SAAO,IAAI,SAAS,kBAAkB,aAAa,IAAI,IAAI,IAAI,IAAI;AAAA,IACjE,KAAK,OAAO,IAAI;AAAA,IAChB,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;","names":[]}
|