tenjin-cli 0.1.0-alpha.15 → 0.1.0-alpha.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +54 -7
- package/README.md +43 -310
- package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-2BKS2FVE.js +93 -0
- package/dist/chunk-2BKS2FVE.js.map +1 -0
- package/dist/chunk-2G2WLVHB.js +102 -0
- package/dist/chunk-2G2WLVHB.js.map +1 -0
- package/dist/chunk-2I4QTOLB.js +11 -0
- package/dist/chunk-2I4QTOLB.js.map +1 -0
- package/dist/chunk-2JGT3KDW.js +172 -0
- package/dist/chunk-2JGT3KDW.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/chunk-35M3VITA.js +102 -0
- package/dist/chunk-35M3VITA.js.map +1 -0
- package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
- package/dist/chunk-3AUDA53C.js.map +1 -0
- package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
- package/dist/chunk-56MOAIP5.js.map +1 -0
- package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5QHHRMRA.js +227 -0
- package/dist/chunk-5QHHRMRA.js.map +1 -0
- package/dist/{chunk-JBIKAAT3.js → chunk-5UDD5VSY.js} +8 -8
- package/dist/chunk-5UDD5VSY.js.map +1 -0
- package/dist/chunk-7QKHZQKW.js +1680 -0
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/{chunk-ZFJJ3EXC.js → chunk-AR7U7BRG.js} +550 -182
- package/dist/chunk-AR7U7BRG.js.map +1 -0
- package/dist/chunk-AUKDYPPX.js +130 -0
- package/dist/chunk-AUKDYPPX.js.map +1 -0
- package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
- package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
- package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
- package/dist/chunk-EGELTSPU.js.map +1 -0
- package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-J5INH7WB.js +299 -0
- package/dist/chunk-J5INH7WB.js.map +1 -0
- package/dist/chunk-JLEF5WHM.js +132 -0
- package/dist/chunk-JLEF5WHM.js.map +1 -0
- package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-KK4YGYTV.js +808 -0
- package/dist/chunk-KK4YGYTV.js.map +1 -0
- package/dist/{chunk-CPCX67TI.js → chunk-KUBEYXSO.js} +1076 -1038
- package/dist/chunk-KUBEYXSO.js.map +1 -0
- package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
- package/dist/{chunk-NIKXHWOL.js → chunk-LJ4DMVFI.js} +16 -16
- package/dist/chunk-LJ4DMVFI.js.map +1 -0
- package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-HPJGOLTN.js → chunk-MRGADYDD.js} +13 -8
- package/dist/chunk-MRGADYDD.js.map +1 -0
- package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-O4ZNKFRU.js +366 -0
- package/dist/chunk-O4ZNKFRU.js.map +1 -0
- package/dist/chunk-PDA2BVFY.js +244 -0
- package/dist/chunk-PDA2BVFY.js.map +1 -0
- package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-QDD2RN7G.js +10238 -0
- package/dist/chunk-QDD2RN7G.js.map +1 -0
- package/dist/chunk-S2NRVRPF.js +171 -0
- package/dist/chunk-S2NRVRPF.js.map +1 -0
- package/dist/chunk-TGLKKLQG.js +11 -0
- package/dist/chunk-TGLKKLQG.js.map +1 -0
- package/dist/chunk-TP4D47BY.js +127 -0
- package/dist/chunk-TP4D47BY.js.map +1 -0
- package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/{chunk-UO22YNY4.js → chunk-U2DZISAH.js} +43 -1
- package/dist/chunk-U2DZISAH.js.map +1 -0
- package/dist/chunk-WGQVJM56.js +165 -0
- package/dist/chunk-WGQVJM56.js.map +1 -0
- package/dist/{chunk-OLWTRUTS.js → chunk-WLMJE3GJ.js} +35 -16
- package/dist/chunk-WLMJE3GJ.js.map +1 -0
- package/dist/chunk-WS4JA6TC.js +137 -0
- package/dist/chunk-WS4JA6TC.js.map +1 -0
- package/dist/chunk-WXC57XGG.js +29 -0
- package/dist/chunk-WXC57XGG.js.map +1 -0
- package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/chunk-XZOEUYMX.js +1784 -0
- package/dist/chunk-XZOEUYMX.js.map +1 -0
- package/dist/{cli-KKRKBU5T.js → cli-VHYYYYXM.js} +303 -374
- package/dist/cli-VHYYYYXM.js.map +1 -0
- package/dist/config-5ADBAAXU.js +42 -0
- package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
- package/dist/doctor-Q35VQW3S.js +436 -0
- package/dist/doctor-Q35VQW3S.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/{chunk-KAJZHIQ4.js → fund-GDDPL2BB.js} +81 -24
- package/dist/fund-GDDPL2BB.js.map +1 -0
- package/dist/hook-command-PBERPRE3.js +763 -0
- package/dist/hook-command-PBERPRE3.js.map +1 -0
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/install-OKDKGUXM.js +60 -0
- package/dist/install-wallet-SI4LZ73K.js +106 -0
- package/dist/install-wallet-SI4LZ73K.js.map +1 -0
- package/dist/{run-XYTQ5TWQ.js → mcp-XX3WRQEZ.js} +3766 -10677
- package/dist/mcp-XX3WRQEZ.js.map +1 -0
- package/dist/paths-P2N4JTDZ.js +49 -0
- package/dist/pay-3SYKHKWJ.js +39 -0
- package/dist/redact-6W23GGJC.js +15 -0
- package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/{send-G746D7PQ.js → send-LQRKTEJT.js} +29 -29
- package/dist/send-LQRKTEJT.js.map +1 -0
- package/dist/{chunk-QZ6ROAJU.js → skill-placement-JMDPSKE6.js} +155 -10
- package/dist/skill-placement-JMDPSKE6.js.map +1 -0
- package/dist/status-FFC6FO72.js +64 -0
- package/dist/status-FFC6FO72.js.map +1 -0
- package/dist/status-line-SAXSU6CR.js +87 -0
- package/dist/status-line-SAXSU6CR.js.map +1 -0
- package/dist/status-line-wiring-L2WYIYBM.js +29 -0
- package/dist/tenjin-daemon.mjs +20421 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-OACH27UV.js +147 -0
- package/dist/uninstall-OACH27UV.js.map +1 -0
- package/dist/{update-R76LHOZW.js → update-4W6EKLGZ.js} +132 -16
- package/dist/update-4W6EKLGZ.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/wallet-BMEXRR3P.js +32 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +71 -352
- package/docs/safety-model.md +16 -6
- package/package.json +8 -7
- package/LICENSE +0 -21
- package/dist/buy-VIRNSYGN.js +0 -47
- package/dist/chunk-2MYQN7HM.js +0 -247
- package/dist/chunk-2MYQN7HM.js.map +0 -1
- package/dist/chunk-2RF2GIJQ.js +0 -1188
- package/dist/chunk-2RF2GIJQ.js.map +0 -1
- package/dist/chunk-3GL2Z5QK.js +0 -57
- package/dist/chunk-3GL2Z5QK.js.map +0 -1
- package/dist/chunk-47PP7TAG.js.map +0 -1
- package/dist/chunk-4CQIDQOT.js +0 -167
- package/dist/chunk-4CQIDQOT.js.map +0 -1
- package/dist/chunk-4KG27W2S.js +0 -614
- package/dist/chunk-4KG27W2S.js.map +0 -1
- package/dist/chunk-5QQTYWEU.js +0 -199
- package/dist/chunk-5QQTYWEU.js.map +0 -1
- package/dist/chunk-65DTCCJ7.js +0 -21
- package/dist/chunk-65DTCCJ7.js.map +0 -1
- package/dist/chunk-A5DKHMUN.js +0 -173
- package/dist/chunk-A5DKHMUN.js.map +0 -1
- package/dist/chunk-B63XPWQ4.js +0 -246
- package/dist/chunk-B63XPWQ4.js.map +0 -1
- package/dist/chunk-CAR6FHK6.js +0 -105
- package/dist/chunk-CAR6FHK6.js.map +0 -1
- package/dist/chunk-CPCX67TI.js.map +0 -1
- package/dist/chunk-CQBVCYI2.js +0 -162
- package/dist/chunk-CQBVCYI2.js.map +0 -1
- package/dist/chunk-DBU5CXBV.js +0 -4731
- package/dist/chunk-DBU5CXBV.js.map +0 -1
- package/dist/chunk-DHJD77OW.js +0 -81
- package/dist/chunk-DHJD77OW.js.map +0 -1
- package/dist/chunk-EDZSNPE5.js +0 -35
- package/dist/chunk-EDZSNPE5.js.map +0 -1
- package/dist/chunk-EFWZPUTC.js +0 -65
- package/dist/chunk-EFWZPUTC.js.map +0 -1
- package/dist/chunk-EPFL6CTE.js +0 -448
- package/dist/chunk-EPFL6CTE.js.map +0 -1
- package/dist/chunk-GHLVXVZD.js +0 -142
- package/dist/chunk-GHLVXVZD.js.map +0 -1
- package/dist/chunk-H3SOOJ2I.js +0 -580
- package/dist/chunk-H3SOOJ2I.js.map +0 -1
- package/dist/chunk-HPJGOLTN.js.map +0 -1
- package/dist/chunk-HRGBS2PA.js +0 -203
- package/dist/chunk-HRGBS2PA.js.map +0 -1
- package/dist/chunk-ITUXPJIS.js +0 -314
- package/dist/chunk-ITUXPJIS.js.map +0 -1
- package/dist/chunk-JBIKAAT3.js.map +0 -1
- package/dist/chunk-KAJZHIQ4.js.map +0 -1
- package/dist/chunk-KINZ23CV.js.map +0 -1
- package/dist/chunk-LRYV3SK7.js +0 -235
- package/dist/chunk-LRYV3SK7.js.map +0 -1
- package/dist/chunk-M2O56UK7.js.map +0 -1
- package/dist/chunk-MJZZTKCC.js.map +0 -1
- package/dist/chunk-NIKXHWOL.js.map +0 -1
- package/dist/chunk-OKDRDT74.js +0 -209
- package/dist/chunk-OKDRDT74.js.map +0 -1
- package/dist/chunk-OKYSNAS3.js +0 -2144
- package/dist/chunk-OKYSNAS3.js.map +0 -1
- package/dist/chunk-OLWTRUTS.js.map +0 -1
- package/dist/chunk-QQ6ELLSA.js +0 -143
- package/dist/chunk-QQ6ELLSA.js.map +0 -1
- package/dist/chunk-QZ6ROAJU.js.map +0 -1
- package/dist/chunk-R7RSCBI7.js +0 -794
- package/dist/chunk-R7RSCBI7.js.map +0 -1
- package/dist/chunk-SGK2B724.js +0 -67
- package/dist/chunk-SGK2B724.js.map +0 -1
- package/dist/chunk-U6VPKMGC.js +0 -390
- package/dist/chunk-U6VPKMGC.js.map +0 -1
- package/dist/chunk-UHTVXQ2O.js +0 -140
- package/dist/chunk-UHTVXQ2O.js.map +0 -1
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-US456VUI.js +0 -149
- package/dist/chunk-US456VUI.js.map +0 -1
- package/dist/chunk-V44J2MXV.js +0 -400
- package/dist/chunk-V44J2MXV.js.map +0 -1
- package/dist/chunk-VJQKL3YH.js +0 -216
- package/dist/chunk-VJQKL3YH.js.map +0 -1
- package/dist/chunk-VJSQSLBM.js +0 -1442
- package/dist/chunk-VJSQSLBM.js.map +0 -1
- package/dist/chunk-VYOJOX4Z.js +0 -165
- package/dist/chunk-VYOJOX4Z.js.map +0 -1
- package/dist/chunk-WY2K35OL.js +0 -269
- package/dist/chunk-WY2K35OL.js.map +0 -1
- package/dist/chunk-ZFJJ3EXC.js.map +0 -1
- package/dist/chunk-ZOBNS7CX.js.map +0 -1
- package/dist/cli-KKRKBU5T.js.map +0 -1
- package/dist/config-JMRUNYE6.js +0 -37
- package/dist/discover-B5HF6SHM.js +0 -102
- package/dist/discover-B5HF6SHM.js.map +0 -1
- package/dist/doctor-ZBG7X66D.js +0 -32
- package/dist/edit-PZJIILQE.js +0 -40
- package/dist/fund-EUDH5KPA.js +0 -40
- package/dist/inspect-QC6WEQPN.js +0 -37
- package/dist/install-GNK2W3PI.js +0 -972
- package/dist/install-GNK2W3PI.js.map +0 -1
- package/dist/outcome-KSGWZHUS.js +0 -24
- package/dist/pay-BC4UICPA.js +0 -361
- package/dist/pay-BC4UICPA.js.map +0 -1
- package/dist/publish-LXWFDIKF.js +0 -42
- package/dist/read-JMNUQ56P.js +0 -160
- package/dist/read-JMNUQ56P.js.map +0 -1
- package/dist/run-XYTQ5TWQ.js.map +0 -1
- package/dist/search-TSQAB45E.js +0 -25
- package/dist/secp256k1-XRPVBC6V.js.map +0 -1
- package/dist/send-G746D7PQ.js.map +0 -1
- package/dist/session-JBKWMJ24.js +0 -89
- package/dist/session-JBKWMJ24.js.map +0 -1
- package/dist/skill-heal-WKD67SLJ.js +0 -92
- package/dist/skill-heal-WKD67SLJ.js.map +0 -1
- package/dist/skill-placement-RIU4AMC2.js +0 -20
- package/dist/skill-placement-RIU4AMC2.js.map +0 -1
- package/dist/uninstall-5E263VTS.js +0 -73
- package/dist/uninstall-5E263VTS.js.map +0 -1
- package/dist/update-R76LHOZW.js.map +0 -1
- package/dist/usdc-4VCDHFWX.js +0 -38
- package/dist/usdc-4VCDHFWX.js.map +0 -1
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
- package/dist/wallet-TQ7D5EQ7.js +0 -41
- package/dist/wallet-TQ7D5EQ7.js.map +0 -1
- package/dist/wallet-ZAVXWLWP.js +0 -32
- package/dist/wallet-ZAVXWLWP.js.map +0 -1
- package/docs/command-reference.md +0 -303
- package/skills/tenjin/SKILL.md +0 -373
- package/skills/tenjin-pay/SKILL.md +0 -76
- package/skills/tenjin-publish/SKILL.md +0 -227
- package/skills/tenjin-publish/references/maintain.md +0 -39
- package/skills/tenjin-search/SKILL.md +0 -154
- package/skills/tenjin-search/references/permissions.md +0 -112
- /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
- /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{ccip-ZGGWQN4X.js.map → config-5ADBAAXU.js.map} +0 -0
- /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
- /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{doctor-ZBG7X66D.js.map → install-OKDKGUXM.js.map} +0 -0
- /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-3SYKHKWJ.js.map} +0 -0
- /package/dist/{fund-EUDH5KPA.js.map → redact-6W23GGJC.js.map} +0 -0
- /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
- /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
- /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
- /package/dist/{search-TSQAB45E.js.map → wallet-BMEXRR3P.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA2GjC,eAAsB,QACpB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AM,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":[]}
|
package/dist/chunk-5QQTYWEU.js
DELETED
|
@@ -1,199 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
composeUserAgent
|
|
4
|
-
} from "./chunk-3GL2Z5QK.js";
|
|
5
|
-
import {
|
|
6
|
-
CliError
|
|
7
|
-
} from "./chunk-ZFJJ3EXC.js";
|
|
8
|
-
|
|
9
|
-
// src/lib/http.ts
|
|
10
|
-
function applyUserAgent(headers, callerUserAgent) {
|
|
11
|
-
headers.set("user-agent", composeUserAgent({ caller: callerUserAgent }));
|
|
12
|
-
return headers;
|
|
13
|
-
}
|
|
14
|
-
function withUserAgent(callerHeaders, callerUserAgent) {
|
|
15
|
-
return Object.fromEntries(
|
|
16
|
-
applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries()
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
20
|
-
"sign-in-with-x",
|
|
21
|
-
"payment-signature",
|
|
22
|
-
"x-payment",
|
|
23
|
-
"tenjin-session-delegation"
|
|
24
|
-
]);
|
|
25
|
-
function carriesSignedMaterial(headers) {
|
|
26
|
-
return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
|
|
27
|
-
}
|
|
28
|
-
async function fetchJson(url, opts) {
|
|
29
|
-
const doFetch = opts.fetchImpl ?? fetch;
|
|
30
|
-
const controller = new AbortController();
|
|
31
|
-
let timedOut = false;
|
|
32
|
-
const timer = setTimeout(() => {
|
|
33
|
-
timedOut = true;
|
|
34
|
-
controller.abort();
|
|
35
|
-
}, opts.timeoutMs);
|
|
36
|
-
try {
|
|
37
|
-
let res;
|
|
38
|
-
try {
|
|
39
|
-
res = await doFetch(url, {
|
|
40
|
-
signal: controller.signal,
|
|
41
|
-
headers: withUserAgent(opts.headers, opts.callerUserAgent)
|
|
42
|
-
});
|
|
43
|
-
} catch (err) {
|
|
44
|
-
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
45
|
-
}
|
|
46
|
-
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
47
|
-
if (!res.ok) {
|
|
48
|
-
return {
|
|
49
|
-
ok: false,
|
|
50
|
-
kind: "http",
|
|
51
|
-
status: res.status,
|
|
52
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
53
|
-
message: `Request to ${url} failed with status ${res.status}`
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
let json;
|
|
57
|
-
try {
|
|
58
|
-
json = await res.json();
|
|
59
|
-
} catch (err) {
|
|
60
|
-
if (timedOut) return timeoutFailure(url, opts.timeoutMs);
|
|
61
|
-
if (err instanceof SyntaxError) {
|
|
62
|
-
return {
|
|
63
|
-
ok: false,
|
|
64
|
-
kind: "invalid-json",
|
|
65
|
-
status: res.status,
|
|
66
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
67
|
-
message: `Response from ${url} was not valid JSON`
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
return {
|
|
71
|
-
ok: false,
|
|
72
|
-
kind: "network",
|
|
73
|
-
status: res.status,
|
|
74
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
75
|
-
message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
return {
|
|
79
|
-
ok: true,
|
|
80
|
-
status: res.status,
|
|
81
|
-
json,
|
|
82
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
83
|
-
};
|
|
84
|
-
} finally {
|
|
85
|
-
clearTimeout(timer);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
function timeoutFailure(url, timeoutMs) {
|
|
89
|
-
return {
|
|
90
|
-
ok: false,
|
|
91
|
-
kind: "timeout",
|
|
92
|
-
message: `Request to ${url} timed out after ${timeoutMs}ms`
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
function prepareRequest(url, opts) {
|
|
96
|
-
try {
|
|
97
|
-
let body;
|
|
98
|
-
const merged = new Headers(opts.headers ?? {});
|
|
99
|
-
if (opts.jsonBody !== void 0) {
|
|
100
|
-
body = JSON.stringify(opts.jsonBody);
|
|
101
|
-
merged.set("content-type", "application/json");
|
|
102
|
-
}
|
|
103
|
-
const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
|
|
104
|
-
if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
|
|
105
|
-
const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
|
|
106
|
-
const signed = carriesSignedMaterial(headers);
|
|
107
|
-
return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };
|
|
108
|
-
} catch (err) {
|
|
109
|
-
return {
|
|
110
|
-
ok: false,
|
|
111
|
-
kind: "network",
|
|
112
|
-
message: `Request to ${url} failed: ${errorMessage(err)}`
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
async function httpRequest(url, opts) {
|
|
117
|
-
const doFetch = opts.fetchImpl ?? fetch;
|
|
118
|
-
const controller = new AbortController();
|
|
119
|
-
let timedOut = false;
|
|
120
|
-
const timer = setTimeout(() => {
|
|
121
|
-
timedOut = true;
|
|
122
|
-
controller.abort();
|
|
123
|
-
}, opts.timeoutMs);
|
|
124
|
-
try {
|
|
125
|
-
const prepared = prepareRequest(url, opts);
|
|
126
|
-
if (!prepared.ok) return prepared;
|
|
127
|
-
const { headers, body, signed, pinned } = prepared;
|
|
128
|
-
let res;
|
|
129
|
-
try {
|
|
130
|
-
res = await doFetch(url, {
|
|
131
|
-
method: opts.method ?? "GET",
|
|
132
|
-
headers,
|
|
133
|
-
body,
|
|
134
|
-
signal: controller.signal,
|
|
135
|
-
...pinned ? { redirect: "manual" } : {}
|
|
136
|
-
});
|
|
137
|
-
} catch (err) {
|
|
138
|
-
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
139
|
-
}
|
|
140
|
-
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
141
|
-
if (pinned && res.status >= 300 && res.status < 400) {
|
|
142
|
-
return {
|
|
143
|
-
ok: false,
|
|
144
|
-
kind: "blocked-redirect",
|
|
145
|
-
status: res.status,
|
|
146
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
147
|
-
message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
let text;
|
|
151
|
-
try {
|
|
152
|
-
text = await res.text();
|
|
153
|
-
} catch (err) {
|
|
154
|
-
if (timedOut) return timeoutFailure(url, opts.timeoutMs);
|
|
155
|
-
return {
|
|
156
|
-
ok: false,
|
|
157
|
-
kind: "network",
|
|
158
|
-
status: res.status,
|
|
159
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
160
|
-
message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
let json;
|
|
164
|
-
if (text.length > 0) {
|
|
165
|
-
try {
|
|
166
|
-
json = JSON.parse(text);
|
|
167
|
-
} catch {
|
|
168
|
-
json = void 0;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
ok: true,
|
|
173
|
-
status: res.status,
|
|
174
|
-
header: (name) => res.headers.get(name) ?? void 0,
|
|
175
|
-
json,
|
|
176
|
-
text,
|
|
177
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
178
|
-
};
|
|
179
|
-
} finally {
|
|
180
|
-
clearTimeout(timer);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
function fetchFailureToCliError(failure, opts = {}) {
|
|
184
|
-
const code = failure.kind === "network" || failure.kind === "timeout" ? "NETWORK_ERROR" : failure.kind === "invalid-json" ? "CONTRACT_MISMATCH" : "API_UNREACHABLE";
|
|
185
|
-
return new CliError(code, failure.message, {
|
|
186
|
-
...opts.fix !== void 0 ? { fix: opts.fix } : {},
|
|
187
|
-
...opts.details !== void 0 ? { details: opts.details } : {}
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
function errorMessage(err) {
|
|
191
|
-
return err instanceof Error ? err.message : String(err);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
export {
|
|
195
|
-
fetchJson,
|
|
196
|
-
httpRequest,
|
|
197
|
-
fetchFailureToCliError
|
|
198
|
-
};
|
|
199
|
-
//# sourceMappingURL=chunk-5QQTYWEU.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,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,MAC3C;AAAA,MACA;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":[]}
|
package/dist/chunk-65DTCCJ7.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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":[]}
|
package/dist/chunk-A5DKHMUN.js
DELETED
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
withFileLock
|
|
4
|
-
} from "./chunk-ZOBNS7CX.js";
|
|
5
|
-
import {
|
|
6
|
-
external_exports,
|
|
7
|
-
writeFileAtomic
|
|
8
|
-
} from "./chunk-ZFJJ3EXC.js";
|
|
9
|
-
|
|
10
|
-
// src/lib/search-store.ts
|
|
11
|
-
import { mkdir, readFile } from "fs/promises";
|
|
12
|
-
import { join } from "path";
|
|
13
|
-
var MAX_ENTRIES = 50;
|
|
14
|
-
var DEMAND_MAX_ENTRIES = 15;
|
|
15
|
-
var StoredCandidateSchema = external_exports.object({
|
|
16
|
-
resourceId: external_exports.string(),
|
|
17
|
-
url: external_exports.string(),
|
|
18
|
-
title: external_exports.string(),
|
|
19
|
-
price: external_exports.string()
|
|
20
|
-
});
|
|
21
|
-
var SearchResolutionSchema = external_exports.enum(["outcome", "publish", "candidate"]);
|
|
22
|
-
var SearchSourceSchema = external_exports.enum(["cli", "websearch-hook", "dispatch-hook"]);
|
|
23
|
-
var StoredSearchSchema = external_exports.object({
|
|
24
|
-
searchId: external_exports.string(),
|
|
25
|
-
at: external_exports.string(),
|
|
26
|
-
question: external_exports.string(),
|
|
27
|
-
decision: external_exports.string(),
|
|
28
|
-
candidates: external_exports.array(StoredCandidateSchema),
|
|
29
|
-
/** Absent until something closes the loop; see {@link markSearchResolved}. */
|
|
30
|
-
resolved: external_exports.object({ by: SearchResolutionSchema, at: external_exports.string() }).optional(),
|
|
31
|
-
/** Absent on entries written before sources existed; see {@link SearchSourceSchema}. */
|
|
32
|
-
source: SearchSourceSchema.optional(),
|
|
33
|
-
/**
|
|
34
|
-
* The harness session this search was run in, when anything could attribute it.
|
|
35
|
-
* This ledger is MACHINE-GLOBAL, so without it the Stop hook nags whichever
|
|
36
|
-
* session happens to stop next about open loops belonging to a sibling session,
|
|
37
|
-
* which that session cannot act on. The hook scopes on this when both the entry
|
|
38
|
-
* and the turn-end payload name a session, and stays global otherwise, so an
|
|
39
|
-
* unstamped entry is still raised everywhere rather than nowhere.
|
|
40
|
-
*
|
|
41
|
-
* OPTIONAL: the WebSearch hook is handed one by the harness (`session_id` on
|
|
42
|
-
* its stdin payload), and a deliberate `tenjin search` reads the same value
|
|
43
|
-
* from CLAUDE_CODE_SESSION_ID (or an operator's TENJIN_SESSION_ID). Absent on
|
|
44
|
-
* entries written before this field existed, and on any harness that exports
|
|
45
|
-
* neither.
|
|
46
|
-
*/
|
|
47
|
-
sessionId: external_exports.string().optional(),
|
|
48
|
-
// How many of the search's browse pointers cost money, and NOT the pointers
|
|
49
|
-
// themselves: keeping them out of the store is what makes `buy <resourceId>`
|
|
50
|
-
// unable to reach one (see the browse comment in agent-api.ts), and a count
|
|
51
|
-
// cannot undo that. It exists so `outcome` can tell "this search offered
|
|
52
|
-
// nothing to buy" from "this search offered a payable browse tail", which the
|
|
53
|
-
// candidates array alone cannot say. Counts only PAID pointers because a
|
|
54
|
-
// zero-priced piece is delivered by `read` with no purchase to decline.
|
|
55
|
-
// Optional because entries written before this field existed have no answer,
|
|
56
|
-
// and `undefined` must read as unknown rather than as zero.
|
|
57
|
-
paidBrowseCount: external_exports.number().int().nonnegative().optional()
|
|
58
|
-
});
|
|
59
|
-
var StoreSchema = external_exports.object({
|
|
60
|
-
schemaVersion: external_exports.literal(1),
|
|
61
|
-
searches: external_exports.array(StoredSearchSchema)
|
|
62
|
-
});
|
|
63
|
-
function searchStorePath(dataDir) {
|
|
64
|
-
return join(dataDir, "searches.json");
|
|
65
|
-
}
|
|
66
|
-
function storePath(dataDir) {
|
|
67
|
-
return searchStorePath(dataDir);
|
|
68
|
-
}
|
|
69
|
-
async function loadSearches(dataDir) {
|
|
70
|
-
let raw;
|
|
71
|
-
try {
|
|
72
|
-
raw = await readFile(storePath(dataDir), "utf8");
|
|
73
|
-
} catch {
|
|
74
|
-
return [];
|
|
75
|
-
}
|
|
76
|
-
let json;
|
|
77
|
-
try {
|
|
78
|
-
json = JSON.parse(raw);
|
|
79
|
-
} catch {
|
|
80
|
-
return [];
|
|
81
|
-
}
|
|
82
|
-
const parsed = StoreSchema.safeParse(json);
|
|
83
|
-
return parsed.success ? parsed.data.searches : [];
|
|
84
|
-
}
|
|
85
|
-
function budgeted(entries) {
|
|
86
|
-
const kept = [];
|
|
87
|
-
let demand = 0;
|
|
88
|
-
for (const entry of entries) {
|
|
89
|
-
if (entry.source === "dispatch-hook") {
|
|
90
|
-
if (demand >= DEMAND_MAX_ENTRIES) continue;
|
|
91
|
-
demand += 1;
|
|
92
|
-
}
|
|
93
|
-
kept.push(entry);
|
|
94
|
-
}
|
|
95
|
-
return kept.slice(0, MAX_ENTRIES);
|
|
96
|
-
}
|
|
97
|
-
async function recordSearch(dataDir, entry) {
|
|
98
|
-
await mkdir(dataDir, { recursive: true, mode: 448 });
|
|
99
|
-
const lockPath = `${storePath(dataDir)}.lock`;
|
|
100
|
-
await withFileLock(lockPath, async () => {
|
|
101
|
-
const existing = await loadSearches(dataDir);
|
|
102
|
-
const searches = budgeted([entry, ...existing.filter((l) => l.searchId !== entry.searchId)]);
|
|
103
|
-
await writeFileAtomic(
|
|
104
|
-
storePath(dataDir),
|
|
105
|
-
`${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}
|
|
106
|
-
`,
|
|
107
|
-
{ mode: 420, dirMode: 448 }
|
|
108
|
-
);
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
async function markSearchResolved(dataDir, searchId, by, at = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
|
|
112
|
-
try {
|
|
113
|
-
const lockPath = `${storePath(dataDir)}.lock`;
|
|
114
|
-
let outcome = "not-found";
|
|
115
|
-
await withFileLock(lockPath, async () => {
|
|
116
|
-
const existing = await loadSearches(dataDir);
|
|
117
|
-
const target = existing.find((s) => s.searchId === searchId);
|
|
118
|
-
if (target === void 0) return;
|
|
119
|
-
if (target.resolved !== void 0) {
|
|
120
|
-
if (options.relink !== true || target.resolved.by === by) {
|
|
121
|
-
outcome = "already-resolved";
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
outcome = "relinked";
|
|
125
|
-
}
|
|
126
|
-
const searches = existing.map(
|
|
127
|
-
(s) => s.searchId === searchId ? { ...s, resolved: { by, at } } : s
|
|
128
|
-
);
|
|
129
|
-
await writeFileAtomic(
|
|
130
|
-
storePath(dataDir),
|
|
131
|
-
`${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}
|
|
132
|
-
`,
|
|
133
|
-
{ mode: 420, dirMode: 448 }
|
|
134
|
-
);
|
|
135
|
-
if (outcome !== "relinked") outcome = "resolved";
|
|
136
|
-
});
|
|
137
|
-
return outcome;
|
|
138
|
-
} catch {
|
|
139
|
-
return "failed";
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
async function latestSearch(dataDir) {
|
|
143
|
-
const searches = await loadSearches(dataDir);
|
|
144
|
-
return searches.find((s) => s.source === void 0 || s.source === "cli") ?? null;
|
|
145
|
-
}
|
|
146
|
-
async function findStoredCandidate(dataDir, resourceId) {
|
|
147
|
-
for (const search of await loadSearches(dataDir)) {
|
|
148
|
-
const hit = search.candidates.find((c) => c.resourceId === resourceId);
|
|
149
|
-
if (hit) return hit;
|
|
150
|
-
}
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
async function findSearchForResource(dataDir, match) {
|
|
154
|
-
for (const search of await loadSearches(dataDir)) {
|
|
155
|
-
const hit = search.candidates.some(
|
|
156
|
-
(c) => match.resourceId !== void 0 && c.resourceId === match.resourceId || match.url !== void 0 && c.url === match.url
|
|
157
|
-
);
|
|
158
|
-
if (hit) return search.searchId;
|
|
159
|
-
}
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
export {
|
|
164
|
-
MAX_ENTRIES,
|
|
165
|
-
DEMAND_MAX_ENTRIES,
|
|
166
|
-
loadSearches,
|
|
167
|
-
recordSearch,
|
|
168
|
-
markSearchResolved,
|
|
169
|
-
latestSearch,
|
|
170
|
-
findStoredCandidate,
|
|
171
|
-
findSearchForResource
|
|
172
|
-
};
|
|
173
|
-
//# sourceMappingURL=chunk-A5DKHMUN.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/search-store.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomic } from './atomic-json';\nimport { withFileLock } from './lock';\n\n/**\n * A small local ledger of recent searches so `outcome --last` can target the most\n * recent one and `buy <resourceId>` can resolve the payable read URL a candidate\n * carried (the read route is keyed by handle/slug, not id, so an id alone can't\n * build the URL). Bounded and best-effort: a corrupt file reads as empty rather\n * than blocking a command. NOT an entitlement record, that is the library receipt.\n */\n\n/**\n * The store's bounds, EXPORTED because lib/hook-scripts.ts bakes them into the\n * scripts it generates, which cannot import this module: one definition, no\n * drift. `DEMAND_MAX_ENTRIES` is the share `dispatch-hook` entries may hold —\n * nothing ever closes one, so without a budget a wide fan-out drains the slots\n * `buy` and `outcome --last` depend on.\n */\nexport const MAX_ENTRIES = 50;\nexport const DEMAND_MAX_ENTRIES = 15;\n\nconst StoredCandidateSchema = z.object({\n resourceId: z.string(),\n url: z.string(),\n title: z.string(),\n price: z.string(),\n});\nexport type StoredCandidate = z.infer<typeof StoredCandidateSchema>;\n\n/**\n * What closed an open loop. The Stop hook stays quiet once any of these is\n * recorded: `outcome` (the loop was reported) or `publish` (the answer went back\n * to the marketplace).\n *\n * `candidate` is RETAINED but never written. It is what the removed candidate\n * pen recorded, and an older `searches.json` still carries it; dropping the\n * member would make those entries fail to parse and read as an empty store,\n * which would resurrect loops their owner already closed.\n */\nexport const SearchResolutionSchema = z.enum(['outcome', 'publish', 'candidate']);\nexport type SearchResolution = z.infer<typeof SearchResolutionSchema>;\n\n/**\n * Who ran the search. `cli` is a deliberate `tenjin search`: the agent decided\n * the question was worth looking up, so an unanswered one is a strong signal.\n * `websearch-hook` is the PreToolUse hook riding along with a WebSearch the agent\n * was going to run anyway, which is a much weaker signal, because nobody judged\n * the question suitable for the marketplace before it was sent.\n *\n * `dispatch-hook` is weaker still: DEMAND DATA about what an agent was about to\n * research, which the Stop hook never raises and which holds a bounded share of\n * the store, because nothing ever closes one.\n *\n * The distinction exists because the Stop hook must not treat them alike: an\n * unanswered deliberate search deserves being named on its own, while a batch of\n * hook searches deserves one line the agent can dismiss at a glance. Keeping them\n * all in ONE store is what makes a hook's misses reachable by explicit\n * `outcome --search-id`, `buy <resourceId>`, and the open-loop reminder at all\n * (`--last` deliberately skips hook entries; see {@link latestSearch}).\n *\n * OPTIONAL, and absent means `cli`: a store written by an earlier version has no\n * source field, and those entries were all explicit searches.\n */\nexport const SearchSourceSchema = z.enum(['cli', 'websearch-hook', 'dispatch-hook']);\nexport type SearchSource = z.infer<typeof SearchSourceSchema>;\n\nconst StoredSearchSchema = z.object({\n searchId: z.string(),\n at: z.string(),\n question: z.string(),\n decision: z.string(),\n candidates: z.array(StoredCandidateSchema),\n /** Absent until something closes the loop; see {@link markSearchResolved}. */\n resolved: z.object({ by: SearchResolutionSchema, at: z.string() }).optional(),\n /** Absent on entries written before sources existed; see {@link SearchSourceSchema}. */\n source: SearchSourceSchema.optional(),\n /**\n * The harness session this search was run in, when anything could attribute it.\n * This ledger is MACHINE-GLOBAL, so without it the Stop hook nags whichever\n * session happens to stop next about open loops belonging to a sibling session,\n * which that session cannot act on. The hook scopes on this when both the entry\n * and the turn-end payload name a session, and stays global otherwise, so an\n * unstamped entry is still raised everywhere rather than nowhere.\n *\n * OPTIONAL: the WebSearch hook is handed one by the harness (`session_id` on\n * its stdin payload), and a deliberate `tenjin search` reads the same value\n * from CLAUDE_CODE_SESSION_ID (or an operator's TENJIN_SESSION_ID). Absent on\n * entries written before this field existed, and on any harness that exports\n * neither.\n */\n sessionId: z.string().optional(),\n // How many of the search's browse pointers cost money, and NOT the pointers\n // themselves: keeping them out of the store is what makes `buy <resourceId>`\n // unable to reach one (see the browse comment in agent-api.ts), and a count\n // cannot undo that. It exists so `outcome` can tell \"this search offered\n // nothing to buy\" from \"this search offered a payable browse tail\", which the\n // candidates array alone cannot say. Counts only PAID pointers because a\n // zero-priced piece is delivered by `read` with no purchase to decline.\n // Optional because entries written before this field existed have no answer,\n // and `undefined` must read as unknown rather than as zero.\n paidBrowseCount: z.number().int().nonnegative().optional(),\n});\nexport type StoredSearch = z.infer<typeof StoredSearchSchema>;\n\nconst StoreSchema = z.object({\n schemaVersion: z.literal(1),\n searches: z.array(StoredSearchSchema),\n});\n\n/**\n * The store and its lock. Both paths are EXPORTED because the installed hook\n * scripts write this same file from outside the CLI process: they cannot import\n * this module, so they reimplement the lock protocol against this exact path.\n * Two writers of one file must at least agree on where the mutex lives, and a\n * test pins the script's protocol against this one.\n */\nexport function searchStorePath(dataDir: string): string {\n return join(dataDir, 'searches.json');\n}\n\nexport function searchStoreLockPath(dataDir: string): string {\n return `${searchStorePath(dataDir)}.lock`;\n}\n\nfunction storePath(dataDir: string): string {\n return searchStorePath(dataDir);\n}\n\nexport async function loadSearches(dataDir: string): Promise<StoredSearch[]> {\n let raw: string;\n try {\n raw = await readFile(storePath(dataDir), 'utf8');\n } catch {\n return [];\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return [];\n }\n const parsed = StoreSchema.safeParse(json);\n return parsed.success ? parsed.data.searches : [];\n}\n\n/**\n * Demand entries held to their share, then the whole thing capped. Entries are\n * newest-first, so dropping once the budget is spent drops the OLDEST demand\n * entries and spares every deliberate one the plain cap would have taken.\n *\n * ⚠ MIRRORED, MUST UPDATE TOGETHER with `budgeted` in lib/hook-scripts.ts. It\n * lives in BOTH writers so the bound belongs to the store rather than to\n * whichever process wrote last.\n */\nfunction budgeted(entries: StoredSearch[]): StoredSearch[] {\n const kept: StoredSearch[] = [];\n let demand = 0;\n for (const entry of entries) {\n if (entry.source === 'dispatch-hook') {\n if (demand >= DEMAND_MAX_ENTRIES) continue;\n demand += 1;\n }\n kept.push(entry);\n }\n return kept.slice(0, MAX_ENTRIES);\n}\n\n/** Prepend a search (newest first), budget and cap it, persist under a lock so\n * concurrent searches don't drop each other's entry. */\nexport async function recordSearch(dataDir: string, entry: StoredSearch): Promise<void> {\n await mkdir(dataDir, { recursive: true, mode: 0o700 });\n const lockPath = `${storePath(dataDir)}.lock`;\n await withFileLock(lockPath, async () => {\n const existing = await loadSearches(dataDir);\n const searches = budgeted([entry, ...existing.filter((l) => l.searchId !== entry.searchId)]);\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n });\n}\n\n/**\n * What a {@link markSearchResolved} call actually did. Returned rather than\n * swallowed because a caller may REPORT the close to its own user, and \"I tried\"\n * is not \"it happened\": a lock timeout or an unwritable store still leaves the\n * loop open and the reminder due, so a receipt claiming otherwise would be a\n * confident lie. `already-resolved` is a success for anyone asking about the\n * LOOP (something closed it), and a no-op for anyone asking about this call.\n * `relinked` is the one that CHANGED a resolution that was already there.\n */\nexport type ResolutionOutcome =\n 'resolved' | 'relinked' | 'already-resolved' | 'not-found' | 'failed';\n\nexport interface MarkResolvedOptions {\n /**\n * Overwrite a resolution recorded by something else, rather than leaving the\n * first closer in place. Only `publish` passes it, and the reason is the loop\n * this whole ledger exists for: an agent mid-research closes a MISS as\n * `regenerated` because the answer is not written yet, finishes it minutes\n * later, and then has no way to say the piece it just published is what\n * answered that question (tenjin-agent #161). A close is a report of intent at\n * a moment; a publish is the answer arriving, and the answer wins.\n */\n relink?: boolean;\n}\n\n/**\n * Record that something closed the loop on `searchId`, so the Stop hook stops\n * raising it. Best-effort and it NEVER throws: an unknown id (the search aged\n * past MAX_ENTRIES, or came from another machine) writes nothing, and a failure\n * to persist costs one stale nag rather than the command the caller actually\n * ran. The FIRST resolution wins unless the caller asks to {@link\n * MarkResolvedOptions.relink}, so an ordinary `outcome` after a publish still\n * does not rewrite who closed it.\n */\nexport async function markSearchResolved(\n dataDir: string,\n searchId: string,\n by: SearchResolution,\n at: string = new Date().toISOString(),\n options: MarkResolvedOptions = {},\n): Promise<ResolutionOutcome> {\n try {\n const lockPath = `${storePath(dataDir)}.lock`;\n let outcome: ResolutionOutcome = 'not-found';\n await withFileLock(lockPath, async () => {\n const existing = await loadSearches(dataDir);\n const target = existing.find((s) => s.searchId === searchId);\n if (target === undefined) return;\n if (target.resolved !== undefined) {\n // Nothing to relink when the recorded closer is already this one: the\n // loop is where it should be, and rewriting the timestamp would report\n // a change nobody made.\n if (options.relink !== true || target.resolved.by === by) {\n outcome = 'already-resolved';\n return;\n }\n outcome = 'relinked';\n }\n const searches = existing.map((s) =>\n s.searchId === searchId ? { ...s, resolved: { by, at } } : s,\n );\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n // 'relinked' was decided above and survives the write; anything else that\n // reached here closed a loop nothing had closed.\n if (outcome !== 'relinked') outcome = 'resolved';\n });\n return outcome;\n } catch {\n // Bookkeeping for a hook nudge. It must never fail the verb that ran — but\n // the caller is told, so nothing reports a close that did not happen.\n return 'failed';\n }\n}\n\n/**\n * The most recent DELIBERATE search: `--last` means \"the search I just ran\", and\n * in auto mode the hooks prepend a ridealong entry on every web search and every\n * subagent dispatch, so an unfiltered head would routinely re-target `outcome\n * --last` at a query the agent never chose to make (found in dogfooding). Hook\n * entries stay reachable by explicit `--search-id`, which is what the Stop hook's\n * reminder names.\n */\nexport async function latestSearch(dataDir: string): Promise<StoredSearch | null> {\n const searches = await loadSearches(dataDir);\n return searches.find((s) => s.source === undefined || s.source === 'cli') ?? null;\n}\n\n/** The stored candidate for a resourceId across recent searches (newest first). */\nexport async function findStoredCandidate(\n dataDir: string,\n resourceId: string,\n): Promise<StoredCandidate | null> {\n for (const search of await loadSearches(dataDir)) {\n const hit = search.candidates.find((c) => c.resourceId === resourceId);\n if (hit) return hit;\n }\n return null;\n}\n\n/** The most recent searchId that surfaced this resource (by id or url), for\n * purchase attribution (`X-Tenjin-Search-Id`). Null when no local search did. */\nexport async function findSearchForResource(\n dataDir: string,\n match: { resourceId?: string; url?: string },\n): Promise<string | null> {\n for (const search of await loadSearches(dataDir)) {\n const hit = search.candidates.some(\n (c) =>\n (match.resourceId !== undefined && c.resourceId === match.resourceId) ||\n (match.url !== undefined && c.url === match.url),\n );\n if (hit) return search.searchId;\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,YAAY;AAoBd,IAAM,cAAc;AACpB,IAAM,qBAAqB;AAElC,IAAM,wBAAwB,iBAAE,OAAO;AAAA,EACrC,YAAY,iBAAE,OAAO;AAAA,EACrB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA,EAChB,OAAO,iBAAE,OAAO;AAClB,CAAC;AAaM,IAAM,yBAAyB,iBAAE,KAAK,CAAC,WAAW,WAAW,WAAW,CAAC;AAwBzE,IAAM,qBAAqB,iBAAE,KAAK,CAAC,OAAO,kBAAkB,eAAe,CAAC;AAGnF,IAAM,qBAAqB,iBAAE,OAAO;AAAA,EAClC,UAAU,iBAAE,OAAO;AAAA,EACnB,IAAI,iBAAE,OAAO;AAAA,EACb,UAAU,iBAAE,OAAO;AAAA,EACnB,UAAU,iBAAE,OAAO;AAAA,EACnB,YAAY,iBAAE,MAAM,qBAAqB;AAAA;AAAA,EAEzC,UAAU,iBAAE,OAAO,EAAE,IAAI,wBAAwB,IAAI,iBAAE,OAAO,EAAE,CAAC,EAAE,SAAS;AAAA;AAAA,EAE5E,QAAQ,mBAAmB,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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