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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +18 -3
  2. package/dist/{buy-2JBYPHAI.js → buy-VIRNSYGN.js} +24 -23
  3. package/dist/{chunk-QWBUKIP2.js → chunk-2MYQN7HM.js} +66 -27
  4. package/dist/chunk-2MYQN7HM.js.map +1 -0
  5. package/dist/{chunk-DAZAXFSF.js → chunk-2RF2GIJQ.js} +57 -226
  6. package/dist/chunk-2RF2GIJQ.js.map +1 -0
  7. package/dist/{chunk-VEAERJVJ.js → chunk-3GL2Z5QK.js} +23 -9
  8. package/dist/chunk-3GL2Z5QK.js.map +1 -0
  9. package/dist/{chunk-IUQZ4Z7M.js → chunk-4CQIDQOT.js} +6 -1
  10. package/dist/chunk-4CQIDQOT.js.map +1 -0
  11. package/dist/{chunk-IXZJ3JOO.js → chunk-4KG27W2S.js} +10 -10
  12. package/dist/chunk-4KG27W2S.js.map +1 -0
  13. package/dist/{chunk-54AJIO3E.js → chunk-5QQTYWEU.js} +4 -3
  14. package/dist/chunk-5QQTYWEU.js.map +1 -0
  15. package/dist/chunk-65DTCCJ7.js +21 -0
  16. package/dist/chunk-65DTCCJ7.js.map +1 -0
  17. package/dist/{chunk-7NADDA2V.js → chunk-A5DKHMUN.js} +20 -8
  18. package/dist/chunk-A5DKHMUN.js.map +1 -0
  19. package/dist/{chunk-WYLMJQVH.js → chunk-B63XPWQ4.js} +24 -18
  20. package/dist/chunk-B63XPWQ4.js.map +1 -0
  21. package/dist/{chunk-L6G35FU5.js → chunk-CAR6FHK6.js} +5 -5
  22. package/dist/{chunk-7GJQ5RGA.js → chunk-CPCX67TI.js} +20 -22
  23. package/dist/{chunk-7GJQ5RGA.js.map → chunk-CPCX67TI.js.map} +1 -1
  24. package/dist/{chunk-XVPQGCH4.js → chunk-CQBVCYI2.js} +36 -50
  25. package/dist/chunk-CQBVCYI2.js.map +1 -0
  26. package/dist/chunk-DBU5CXBV.js +4731 -0
  27. package/dist/chunk-DBU5CXBV.js.map +1 -0
  28. package/dist/chunk-DHJD77OW.js +81 -0
  29. package/dist/chunk-DHJD77OW.js.map +1 -0
  30. package/dist/{chunk-XGZ5EVMB.js → chunk-EDZSNPE5.js} +2 -2
  31. package/dist/{chunk-736DW4V3.js → chunk-EFWZPUTC.js} +2 -2
  32. package/dist/chunk-EPFL6CTE.js +448 -0
  33. package/dist/chunk-EPFL6CTE.js.map +1 -0
  34. package/dist/{chunk-3P3ES4XU.js → chunk-GHLVXVZD.js} +3 -5
  35. package/dist/{chunk-3P3ES4XU.js.map → chunk-GHLVXVZD.js.map} +1 -1
  36. package/dist/{chunk-4UHNXY6B.js → chunk-H3SOOJ2I.js} +88 -294
  37. package/dist/chunk-H3SOOJ2I.js.map +1 -0
  38. package/dist/{chunk-MJSXP4LW.js → chunk-HPJGOLTN.js} +6 -8
  39. package/dist/{chunk-MJSXP4LW.js.map → chunk-HPJGOLTN.js.map} +1 -1
  40. package/dist/{chunk-J6FUAIRR.js → chunk-HRGBS2PA.js} +4 -6
  41. package/dist/{chunk-J6FUAIRR.js.map → chunk-HRGBS2PA.js.map} +1 -1
  42. package/dist/{chunk-FDUD3W5V.js → chunk-ITUXPJIS.js} +55 -58
  43. package/dist/chunk-ITUXPJIS.js.map +1 -0
  44. package/dist/{chunk-ETKZWJ4B.js → chunk-JBIKAAT3.js} +2 -2
  45. package/dist/{chunk-ETKZWJ4B.js.map → chunk-JBIKAAT3.js.map} +1 -1
  46. package/dist/{chunk-3ZW7HPY5.js → chunk-KAJZHIQ4.js} +13 -10
  47. package/dist/chunk-KAJZHIQ4.js.map +1 -0
  48. package/dist/{chunk-OWVVI4VQ.js → chunk-KINZ23CV.js} +107 -4535
  49. package/dist/chunk-KINZ23CV.js.map +1 -0
  50. package/dist/{chunk-PCX2JQ2J.js → chunk-LRYV3SK7.js} +9 -7
  51. package/dist/{chunk-PCX2JQ2J.js.map → chunk-LRYV3SK7.js.map} +1 -1
  52. package/dist/{chunk-ACBEHJAH.js → chunk-NIKXHWOL.js} +11 -13
  53. package/dist/{chunk-ACBEHJAH.js.map → chunk-NIKXHWOL.js.map} +1 -1
  54. package/dist/chunk-OKDRDT74.js +209 -0
  55. package/dist/chunk-OKDRDT74.js.map +1 -0
  56. package/dist/chunk-OKYSNAS3.js +2144 -0
  57. package/dist/chunk-OKYSNAS3.js.map +1 -0
  58. package/dist/{chunk-B676GPS2.js → chunk-OLWTRUTS.js} +7 -3
  59. package/dist/{chunk-B676GPS2.js.map → chunk-OLWTRUTS.js.map} +1 -1
  60. package/dist/{chunk-WU5CZPLD.js → chunk-QQ6ELLSA.js} +6 -8
  61. package/dist/{chunk-WU5CZPLD.js.map → chunk-QQ6ELLSA.js.map} +1 -1
  62. package/dist/{chunk-NAAMHWSI.js → chunk-QZ6ROAJU.js} +5 -4
  63. package/dist/chunk-QZ6ROAJU.js.map +1 -0
  64. package/dist/{chunk-GEHL43VE.js → chunk-R7RSCBI7.js} +130 -47
  65. package/dist/chunk-R7RSCBI7.js.map +1 -0
  66. package/dist/{chunk-LSWP7MU2.js → chunk-U6VPKMGC.js} +127 -27
  67. package/dist/chunk-U6VPKMGC.js.map +1 -0
  68. package/dist/{chunk-W4VW5XYB.js → chunk-US456VUI.js} +6 -6
  69. package/dist/{chunk-O75FOHXS.js → chunk-V44J2MXV.js} +64 -36
  70. package/dist/chunk-V44J2MXV.js.map +1 -0
  71. package/dist/{chunk-4Y53PDH6.js → chunk-VJQKL3YH.js} +10 -7
  72. package/dist/{chunk-4Y53PDH6.js.map → chunk-VJQKL3YH.js.map} +1 -1
  73. package/dist/{chunk-VRPLZERE.js → chunk-VJSQSLBM.js} +47 -26
  74. package/dist/chunk-VJSQSLBM.js.map +1 -0
  75. package/dist/{chunk-PKW3H26Z.js → chunk-VYOJOX4Z.js} +9 -7
  76. package/dist/chunk-VYOJOX4Z.js.map +1 -0
  77. package/dist/chunk-WY2K35OL.js +269 -0
  78. package/dist/chunk-WY2K35OL.js.map +1 -0
  79. package/dist/{chunk-PAOVPSP6.js → chunk-ZFJJ3EXC.js} +53 -5
  80. package/dist/chunk-ZFJJ3EXC.js.map +1 -0
  81. package/dist/{cli-U2BEUA55.js → cli-KKRKBU5T.js} +71 -40
  82. package/dist/{cli-U2BEUA55.js.map → cli-KKRKBU5T.js.map} +1 -1
  83. package/dist/config-JMRUNYE6.js +37 -0
  84. package/dist/discover-B5HF6SHM.js +102 -0
  85. package/dist/discover-B5HF6SHM.js.map +1 -0
  86. package/dist/doctor-ZBG7X66D.js +32 -0
  87. package/dist/edit-PZJIILQE.js +40 -0
  88. package/dist/{fund-Y5IAHZ5D.js → fund-EUDH5KPA.js} +19 -19
  89. package/dist/index.js +1 -1
  90. package/dist/{inspect-NFQ6SQQQ.js → inspect-QC6WEQPN.js} +20 -20
  91. package/dist/{install-DXX7PVUP.js → install-GNK2W3PI.js} +196 -78
  92. package/dist/install-GNK2W3PI.js.map +1 -0
  93. package/dist/outcome-KSGWZHUS.js +24 -0
  94. package/dist/pay-BC4UICPA.js +361 -0
  95. package/dist/pay-BC4UICPA.js.map +1 -0
  96. package/dist/publish-LXWFDIKF.js +42 -0
  97. package/dist/{read-W7QVRBVD.js → read-JMNUQ56P.js} +21 -21
  98. package/dist/{run-CJWPGMIQ.js → run-XYTQ5TWQ.js} +52 -45
  99. package/dist/{run-CJWPGMIQ.js.map → run-XYTQ5TWQ.js.map} +1 -1
  100. package/dist/search-TSQAB45E.js +25 -0
  101. package/dist/{send-C5EOKXOU.js → send-G746D7PQ.js} +14 -15
  102. package/dist/{send-C5EOKXOU.js.map → send-G746D7PQ.js.map} +1 -1
  103. package/dist/{session-OBCUUIFX.js → session-JBKWMJ24.js} +17 -17
  104. package/dist/{skill-heal-D6EPLPS6.js → skill-heal-WKD67SLJ.js} +17 -9
  105. package/dist/skill-heal-WKD67SLJ.js.map +1 -0
  106. package/dist/skill-placement-RIU4AMC2.js +20 -0
  107. package/dist/{uninstall-OWJNJ5LI.js → uninstall-5E263VTS.js} +12 -12
  108. package/dist/uninstall-5E263VTS.js.map +1 -0
  109. package/dist/{update-24Y2CQTT.js → update-R76LHOZW.js} +7 -8
  110. package/dist/{update-24Y2CQTT.js.map → update-R76LHOZW.js.map} +1 -1
  111. package/dist/{wallet-SLRIYJ2U.js → wallet-TQ7D5EQ7.js} +7 -8
  112. package/dist/{wallet-OFXDIIGP.js → wallet-ZAVXWLWP.js} +11 -12
  113. package/dist/wallet-ZAVXWLWP.js.map +1 -0
  114. package/docs/agent-permissions.md +17 -2
  115. package/docs/command-reference.md +84 -42
  116. package/docs/safety-model.md +9 -0
  117. package/package.json +1 -1
  118. package/skills/tenjin/SKILL.md +38 -29
  119. package/skills/tenjin-pay/SKILL.md +76 -0
  120. package/skills/tenjin-publish/SKILL.md +10 -7
  121. package/skills/tenjin-search/SKILL.md +18 -13
  122. package/skills/tenjin-search/references/permissions.md +9 -3
  123. package/dist/chunk-3ZW7HPY5.js.map +0 -1
  124. package/dist/chunk-4UHNXY6B.js.map +0 -1
  125. package/dist/chunk-54AJIO3E.js.map +0 -1
  126. package/dist/chunk-7NADDA2V.js.map +0 -1
  127. package/dist/chunk-DAZAXFSF.js.map +0 -1
  128. package/dist/chunk-DTCXO7HS.js +0 -791
  129. package/dist/chunk-DTCXO7HS.js.map +0 -1
  130. package/dist/chunk-FDUD3W5V.js.map +0 -1
  131. package/dist/chunk-GEHL43VE.js.map +0 -1
  132. package/dist/chunk-IU2HVT3Y.js +0 -313
  133. package/dist/chunk-IU2HVT3Y.js.map +0 -1
  134. package/dist/chunk-IUQZ4Z7M.js.map +0 -1
  135. package/dist/chunk-IXZJ3JOO.js.map +0 -1
  136. package/dist/chunk-LSWP7MU2.js.map +0 -1
  137. package/dist/chunk-NAAMHWSI.js.map +0 -1
  138. package/dist/chunk-O75FOHXS.js.map +0 -1
  139. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  140. package/dist/chunk-PAOVPSP6.js.map +0 -1
  141. package/dist/chunk-PKW3H26Z.js.map +0 -1
  142. package/dist/chunk-PQZVDCCA.js +0 -125
  143. package/dist/chunk-PQZVDCCA.js.map +0 -1
  144. package/dist/chunk-QWBUKIP2.js.map +0 -1
  145. package/dist/chunk-VEAERJVJ.js.map +0 -1
  146. package/dist/chunk-VRPLZERE.js.map +0 -1
  147. package/dist/chunk-WYLMJQVH.js.map +0 -1
  148. package/dist/chunk-XVPQGCH4.js.map +0 -1
  149. package/dist/chunk-ZQIQ55KK.js +0 -51
  150. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  151. package/dist/config-CNUIX23Q.js +0 -32
  152. package/dist/doctor-QJJXRWTO.js +0 -31
  153. package/dist/edit-HJ44P44P.js +0 -40
  154. package/dist/install-DXX7PVUP.js.map +0 -1
  155. package/dist/outcome-ANV4QIED.js +0 -24
  156. package/dist/publish-PCBTCXCZ.js +0 -42
  157. package/dist/search-JGAVKTYJ.js +0 -25
  158. package/dist/skill-heal-D6EPLPS6.js.map +0 -1
  159. package/dist/uninstall-OWJNJ5LI.js.map +0 -1
  160. /package/dist/{buy-2JBYPHAI.js.map → buy-VIRNSYGN.js.map} +0 -0
  161. /package/dist/{chunk-L6G35FU5.js.map → chunk-CAR6FHK6.js.map} +0 -0
  162. /package/dist/{chunk-XGZ5EVMB.js.map → chunk-EDZSNPE5.js.map} +0 -0
  163. /package/dist/{chunk-736DW4V3.js.map → chunk-EFWZPUTC.js.map} +0 -0
  164. /package/dist/{chunk-W4VW5XYB.js.map → chunk-US456VUI.js.map} +0 -0
  165. /package/dist/{config-CNUIX23Q.js.map → config-JMRUNYE6.js.map} +0 -0
  166. /package/dist/{doctor-QJJXRWTO.js.map → doctor-ZBG7X66D.js.map} +0 -0
  167. /package/dist/{edit-HJ44P44P.js.map → edit-PZJIILQE.js.map} +0 -0
  168. /package/dist/{fund-Y5IAHZ5D.js.map → fund-EUDH5KPA.js.map} +0 -0
  169. /package/dist/{inspect-NFQ6SQQQ.js.map → inspect-QC6WEQPN.js.map} +0 -0
  170. /package/dist/{outcome-ANV4QIED.js.map → outcome-KSGWZHUS.js.map} +0 -0
  171. /package/dist/{publish-PCBTCXCZ.js.map → publish-LXWFDIKF.js.map} +0 -0
  172. /package/dist/{read-W7QVRBVD.js.map → read-JMNUQ56P.js.map} +0 -0
  173. /package/dist/{search-JGAVKTYJ.js.map → search-TSQAB45E.js.map} +0 -0
  174. /package/dist/{session-OBCUUIFX.js.map → session-JBKWMJ24.js.map} +0 -0
  175. /package/dist/{wallet-OFXDIIGP.js.map → skill-placement-RIU4AMC2.js.map} +0 -0
  176. /package/dist/{wallet-SLRIYJ2U.js.map → wallet-TQ7D5EQ7.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/publish.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 } from '../lib/config';\nimport { loadSearches, markSearchResolved, type StoredSearch } from '../lib/search-store';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal, sanitizeWireText } from '../lib/output';\nimport { trimSlash } from '../lib/url';\nimport {\n deriveCard,\n localCardEligibility,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type Frontmatter,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n publishPost,\n normalizeSearchIds,\n EXCERPT_MAX_LENGTH,\n PUBLISH_STATUSES,\n type PublishInput,\n type PublishStatus,\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 publish <file.md>`: read the Markdown, parse\n * frontmatter for post + answer-card fields, run the deterministic scan (every\n * mode), gate on the D38\n * consent cascade, then write via the session key (minted on first use) or the\n * plain-SIWX fallback and return a compact receipt. The ordering is the point and\n * is enforced here: scan and consent BEFORE any wallet touch or network write.\n *\n * Exit codes: 0 success (incl. an ineligible-but-published card), 2 usage, 3\n * needs_confirmation / non-bypassable publish_blocked, 4 a write failure after\n * approval.\n */\n\nexport interface PublishArgs {\n /** The Markdown file to publish. */\n file?: string;\n /** The search(es) this publish answers; closes each open loop. */\n searchId?: string | string[];\n draft?: boolean;\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n /** Top-level post price, decimal USD at the edge (O1). */\n price?: string;\n /** The public preview text; overrides frontmatter `excerpt`. Absent, the server\n * derives one from the body's leading prose. */\n excerpt?: string;\n question?: string[];\n task?: 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}\n\nexport interface PublishDeps {\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 /** How this surface spells the search-id input, for edge errors: the CLI flag\n * by default, `searchId` from the MCP tool. A dep and not an arg because\n * `publishInput`'s `satisfies` would expose a new PublishArgs key to agents. */\n searchIdLabel?: string;\n}\n\nexport async function runPublish(\n args: PublishArgs,\n ctx: CommandContext,\n deps: PublishDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n // Validate --mode at the edge (USAGE, exit 2) BEFORE any consent resolution: a\n // typo like `--mode Review` must never be silently dropped onto a looser mode\n // and publish unconfirmed. Mirrors install's --publish-mode edge check.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n const searchIds = normalizeSearchIds(args.searchId, deps.searchIdLabel ?? '--search-id');\n\n const raw = await readSource(args);\n // Read the named searches ONCE: one prefills the card, and each id's presence\n // decides what its close reports and what is warned about below.\n const stored = await loadNamedSearches(ctx, searchIds);\n const { frontmatter, body } = parseFrontmatter(raw);\n\n const status = resolveStatus(args, frontmatter);\n if (status !== 'draft') warnUnrecorded(ctx, searchIds, stored);\n const title = resolveTitle(frontmatter, body);\n const tags = resolveTags(frontmatter);\n const excerpt = resolveExcerpt(args, frontmatter);\n const handle = expectString(frontmatter, 'handle');\n // The named search's question prefills questionsAnswered, but only as a\n // fallback: an explicit --question OR a frontmatter questionsAnswered still\n // wins. That phrasing is what the next searcher will send.\n const cardFlags = cardFlagsFrom(args);\n // One card, one prefill: the first id you typed that this machine holds.\n const prefillFrom = searchIds.find((id) => stored.get(id)?.question !== undefined);\n const wanted = prefillFrom === undefined ? undefined : stored.get(prefillFrom)?.question;\n const prefillQuestion = wanted === undefined ? undefined : cardQuestion(wanted);\n const roomForPrefill =\n cardFlags.question === undefined && frontmatter.questionsAnswered === undefined;\n if (prefillQuestion !== undefined && roomForPrefill) cardFlags.question = [prefillQuestion];\n // A prefill that was WANTED, had room, and was dropped anyway is the one case a\n // caller cannot infer: the card simply comes back without the question it asked\n // for. Reported on both surfaces, because --json never sees the stderr line.\n const prefill: PrefillOutcome =\n wanted === undefined || !roomForPrefill\n ? 'none'\n : prefillQuestion !== undefined\n ? 'applied'\n : 'dropped-too-long';\n if (prefill === 'dropped-too-long') {\n ctx.io.stderr.write(\n `The searched question is longer than ${CARD_QUESTION_MAX} characters, so it was not added to the answer card; pass --question to set a shorter one.\\n`,\n );\n }\n const card = deriveCard(frontmatter, cardFlags);\n\n // The consent cascade + resolved price (global < project < env < flag), with the\n // full-auto loosening gate. Its downgrade warnings go to stderr, not the receipt.\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n // The resolver's downgrade warnings, a mistyped env mode, and the one-line\n // explainer for an unconfigured mode: all stderr, all invisible to --json.\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each publish asks you once. Set auto to publish clean scans automatically',\n );\n const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);\n\n // The scan runs in EVERY mode (D38): it gates the gate, it does not replace it.\n // Scan the whole file AND the derived card's text, so a secret reaches the same\n // gates whether it arrives in the body, in frontmatter, or via a card-authoring\n // flag (--provenance, --scope, …) — the card ships to the PUBLIC card, so a flag\n // secret must block exactly like an in-file one. Dedupe by check+excerpt so a\n // frontmatter value (present in both raw and the card) is not double-counted.\n // The scan context carries the source project's git remote slugs (offline FS\n // read, best-effort): a draft quoting its own project's repo/org warns as a\n // private-by-default reference (open-questions publishing-safety check-set).\n // Markers derive from the DRAFT's project, not the shell's cwd (review r5): a\n // file publish walks up from the file's own directory, so the process cwd is\n // unrelated to where the draft actually lives.\n const markerRoot = args.file !== undefined ? dirname(resolve(cwd, args.file)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n const findings = dedupeFindings([\n ...scan(raw, scanContext),\n ...scan(cardScanText(card), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n\n const eligibility = localCardEligibility(card);\n const price = toMoney(priceAtomic);\n\n // A hard-block finding refuses in EVERY mode and is never clearable by --yes or\n // full-auto — the same non-bypassable posture as buy's price cap.\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the file (it is never masked away by --yes), then re-run.',\n details: {\n mode: settings.mode,\n findings: blocking.map(publicFinding),\n price: { atomic: price.atomic, usd: price.usd },\n },\n });\n }\n\n // --yes clears the soft findings and the review confirm alike.\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, price.usd), {\n fix: 'Review the findings, then re-run with --yes (or resolve the source and re-run).',\n details: {\n mode: settings.mode,\n price: { atomic: price.atomic, usd: price.usd },\n findings: warns.map(publicFinding),\n card: eligibility,\n target: { status, titlePreview: sanitizeForTerminal(title ?? '(untitled draft)') },\n },\n });\n }\n\n // Approved (or nothing to confirm): from here a wallet is required. The write\n // base URL is resolved through the shared settings seam and used for BOTH the\n // SIWX/session header domain and the POST host, so the two never diverge.\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 const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n // A publish always writes.\n scope: 'read+write',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n\n const input: PublishInput = {\n ...(title !== undefined ? { title } : {}),\n bodyMd: body,\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(tags !== undefined ? { tags } : {}),\n priceAtomic,\n ...(handle !== undefined ? { handle } : {}),\n status,\n ...(card !== undefined ? { resource: card } : {}),\n // The attribution half of `--search-id`, and it follows the SAME rule the\n // local ledger already follows: a draft answers nobody, so it claims nobody's\n // demand either. Sending it on a draft put one demand signal on two posts —\n // no command promotes a draft, so reaching a public piece means a second\n // publish carrying the same id — with one of them possibly never shipping.\n ...(searchIds.length > 0 && status !== 'draft' ? { searchId: searchIds } : {}),\n };\n\n const result = await publishPost(input, auth, {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // A DRAFT answered nobody. It parks the piece privately, so it clears no parked\n // loop: the draft is still the pending answer, and the later real publish is\n // what resolves it.\n const parksPrivately = status === 'draft';\n\n // One close per id, each reporting for itself: the piece is published and the\n // server has every id, so an unrecorded search warns without costing the rest.\n const searches: SearchReceipt[] = [];\n for (const id of searchIds) {\n searches.push(\n await closeNamedSearch(\n ctx,\n id,\n stored.get(id) ?? null,\n parksPrivately,\n id === prefillFrom ? prefill : 'none',\n ),\n );\n }\n return receipt(result, runtime.baseUrl, searches);\n}\n\n/**\n * Which named searches this machine has no record of, said BEFORE the wallet\n * touch: the server takes the batch as a unit, so one id it cannot match refuses\n * the whole publish, after the signature. Ordinary, with a 50-entry store against\n * a 90-day sweep. A warning: an id recorded elsewhere is absent here, valid there.\n */\nfunction warnUnrecorded(\n ctx: CommandContext,\n searchIds: string[],\n stored: Map<string, StoredSearch>,\n): void {\n const unrecorded = searchIds.filter((id) => !stored.has(id));\n if (unrecorded.length === 0) return;\n ctx.io.stderr.write(\n `Not in this machine's search store: ${unrecorded.join(', ')}. The server accepts or refuses the named searches as one batch, so if it has no record of one either, this publish is refused after it is signed. Drop that id to publish without it.\\n`,\n );\n}\n\n/**\n * The local records for the named searches, keyed case-folded like the ids that\n * look them up, so an entry recorded in another spelling is still found.\n */\nasync function loadNamedSearches(\n ctx: CommandContext,\n searchIds: string[],\n): Promise<Map<string, StoredSearch>> {\n if (searchIds.length === 0) return new Map();\n const searches = await loadSearches(ctx.dataDir);\n const wanted = new Set(searchIds);\n return new Map(\n searches\n .filter((s) => wanted.has(s.searchId.toLowerCase()))\n .map((s) => [s.searchId.toLowerCase(), s]),\n );\n}\n\n/**\n * What `--search-id` did, as a machine field. `--json` suppresses every stderr\n * note below, so without this an agent that named a search had no way to learn\n * whether its loop actually closed — the same silent-flag failure the draft note\n * fixes for a human.\n */\ninterface SearchReceipt {\n id: string;\n closed: boolean;\n /**\n * The loop had already been closed by something else (an `outcome` report) and\n * this publish took it over. Reported because it is the one case where naming a\n * search changed a record that was already there.\n */\n relinked?: boolean;\n /**\n * An earlier publish had already closed this loop, so this one attributed\n * nothing new. Distinct from `relinked`, which took a loop over from an\n * `outcome` report.\n */\n alreadyAnswered?: boolean;\n prefill: PrefillOutcome;\n}\n\n/**\n * What became of the searched question as a card entry. `none` covers both \"no\n * stored question\" and \"the draft named its own\", which are the cases where\n * nothing was expected; `dropped-too-long` is the one a caller has to be told.\n */\ntype PrefillOutcome = 'applied' | 'dropped-too-long' | 'none';\n\n/**\n * Close the loop a `--search-id` file publish named, and say what happened in\n * both registers: a stderr line for a human, the returned receipt for `--json`.\n *\n * Two outcomes close nothing, and neither is an error — the piece is already\n * published, and bookkeeping never fails the write that ran. A `--draft` parks\n * privately and answers nobody, and an unknown id (aged out of the local store,\n * or from another machine) has no loop here to close.\n *\n * `closed: true` describes the LOOP, not this call: a search an `outcome` already\n * closed reports closed here too, which is what the caller is actually asking\n * about. It reports the OUTCOME of the write rather than the intent to write, so\n * a swallowed lock timeout comes back as `closed: false` and a stderr line\n * instead of a receipt claiming a close that never landed.\n *\n * A publish RELINKS a loop something else already closed. Closing as\n * `regenerated` is what an agent does when the answer is still being written, so\n * treating that as final is what severed seventeen demand signals from the two\n * pieces that answered them (tenjin-agent #161). Nothing is lost by taking the\n * loop over: the `outcome` report was already sent, and this only records who\n * ended up answering it.\n */\nasync function closeNamedSearch(\n ctx: CommandContext,\n searchId: string,\n stored: StoredSearch | null,\n parksPrivately: boolean,\n prefill: PrefillOutcome,\n): Promise<SearchReceipt> {\n const open = (reason: string): SearchReceipt => {\n ctx.io.stderr.write(`${reason}\\n`);\n return { id: searchId, closed: false, prefill };\n };\n if (parksPrivately) return open(`Saved as a draft, so search ${searchId} stays open.`);\n if (stored === null) {\n return open(`Published, but search ${searchId} is not in the local store.`);\n }\n // The record's OWN spelling: the store matches ids by exact string.\n const outcome = await markSearchResolved(ctx.dataDir, stored.searchId, 'publish', undefined, {\n relink: true,\n });\n if (outcome === 'failed') {\n return open(\n `Published, but the local record for search ${searchId} could not be updated, so the open-loop reminder may repeat. Close it with \\`tenjin outcome --search-id ${searchId} --status used\\`.`,\n );\n }\n // `not-found` here means the entry was evicted between the read above and this\n // write: nothing was closed, so nothing claims to have been.\n if (outcome === 'not-found') {\n return open(`Published, but search ${searchId} is no longer in the local store.`);\n }\n if (outcome === 'relinked') return { id: searchId, closed: true, relinked: true, prefill };\n // A PRIOR publish already closed this loop. Reporting a fresh close here is a\n // receipt for something that did not happen, on the one path where a different\n // post already claims the demand this body is claiming again.\n if (outcome === 'already-resolved' && stored.resolved?.by === 'publish') {\n ctx.io.stderr.write(\n `Search ${searchId} was already answered by an earlier publish; this piece did not claim it.\\n`,\n );\n return { id: searchId, closed: true, alreadyAnswered: true, prefill };\n }\n return { id: searchId, closed: true, prefill };\n}\n\n/** The Markdown to publish. A missing path is USAGE before any wallet touch. */\nasync function readSource(args: PublishArgs): Promise<string> {\n if (args.file === undefined) {\n throw new CliError('USAGE', 'Nothing to publish.', {\n fix: 'Pass a Markdown file, e.g. `tenjin publish post.md`.',\n });\n }\n return readMarkdown(args.file);\n}\n\nfunction receipt(\n result: Awaited<ReturnType<typeof publishPost>>,\n baseUrl: string,\n searches: SearchReceipt[],\n): CommandResult {\n const price = toMoney(result.priceAtomic);\n const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);\n const cacheEligible = result.cacheEligible ?? false;\n const deskUrl = `${trimSlash(baseUrl)}/desk`;\n const title = sanitizeForTerminal(result.title);\n // status and url are server-sent open strings (posts-api declares both as bare\n // z.string()), so they get the same treatment as the title beside them: this\n // line is what an author reads to learn where their piece went.\n const human = [\n `Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD → ${sanitizeForTerminal(result.url)}`,\n cacheEligible\n ? 'Answer card is search-eligible.'\n : missing.length > 0\n ? `Answer card incomplete, ranks below every complete card in agent search. To fix: ${missing.join(' ')}`\n : 'Published without an answer card: ranks below every carded piece in agent search.',\n ...searches.filter((s) => s.closed).map(closeLine),\n ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n data: {\n resourceId: result.resourceId,\n url: result.url,\n status: result.status,\n price,\n cacheEligible,\n missing,\n deskUrl,\n // `search` repeats a lone result for callers that already read it; a\n // batch has no single one to repeat.\n ...(searches.length === 1 ? { search: searches[0] } : {}),\n ...(searches.length > 0 ? { searches } : {}),\n ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),\n },\n humanLines: human,\n };\n}\n\nfunction closeLine(search: SearchReceipt): string {\n if (search.relinked === true) {\n return `Re-linked search ${search.id} to this piece; it had been closed without one.`;\n }\n if (search.alreadyAnswered === true) {\n return `Search ${search.id} was already answered by an earlier publish.`;\n }\n return `Closed the loop on search ${search.id}.`;\n}\n\n// ---------------------------------------------------------------------------\n// Field resolution.\n// ---------------------------------------------------------------------------\n\nasync function readMarkdown(file: string): Promise<string> {\n try {\n return 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 publish post.md`.',\n cause: err,\n });\n }\n}\n\nfunction resolveStatus(args: PublishArgs, frontmatter: Frontmatter): PublishStatus {\n if (args.draft === true) return 'draft';\n const fm = frontmatter.status;\n if (fm === undefined) return 'published';\n if (typeof fm !== 'string' || !(PUBLISH_STATUSES as readonly string[]).includes(fm)) {\n throw new CliError('USAGE', `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {\n fix: 'Use status: draft | published | unlisted, or pass --draft.',\n });\n }\n return fm as PublishStatus;\n}\n\nfunction resolveTitle(frontmatter: Frontmatter, body: string): string | undefined {\n const fm = frontmatter.title;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter title must be a single string.');\n }\n return fm.trim();\n }\n // Fall back to the first heading (level 1 preferred) so a plain `# Title` post\n // needs no frontmatter.\n const headings = headingOutline(body);\n const h1 = headings.find((h) => h.level === 1) ?? headings[0];\n return h1?.text;\n}\n\n/** The server's per-item bound on `questionsAnswered` (mirrored by deriveCard). */\nconst CARD_QUESTION_MAX = 200;\n\n/**\n * A stored question as a card entry, or undefined when it cannot be one.\n *\n * Dropped rather than cut over the item bound: a search question may run to the\n * server's 512, and a prefill that fails card validation would turn a publish\n * that was fine into a usage error the caller never asked for. Truncating is\n * worse still — half a question is a different question, and this text is what\n * the next searcher matches against.\n */\nfunction cardQuestion(raw: string): string | undefined {\n const question = sanitizeWireText(raw);\n return question.length > 0 && question.length <= CARD_QUESTION_MAX ? question : undefined;\n}\n\n/**\n * The public preview text: `--excerpt` over frontmatter `excerpt`, or undefined\n * to let the server derive one from the body's leading prose.\n *\n * The bound is checked HERE as well as in the request builder, because the\n * builder runs after a wallet signature has been collected and this is the edge:\n * a too-long excerpt should cost a message, not a signing prompt. Refused rather\n * than truncated — a silently cut preview is a different preview, and the whole\n * point of setting one is controlling exactly what a non-buyer reads. Sanitized\n * before the bound for the same reason the builder is: the stripped text is what\n * ships, so it is what the length has to describe.\n */\nfunction resolveExcerpt(args: PublishArgs, frontmatter: Frontmatter): string | undefined {\n const raw = args.excerpt ?? expectString(frontmatter, 'excerpt');\n if (raw === undefined) return undefined;\n const excerpt = sanitizeWireText(raw);\n if (excerpt.length > EXCERPT_MAX_LENGTH) {\n throw new CliError(\n 'USAGE',\n `excerpt must be at most ${EXCERPT_MAX_LENGTH} characters (got ${excerpt.length}).`,\n { fix: `Shorten it to ${EXCERPT_MAX_LENGTH} characters or fewer.` },\n );\n }\n return excerpt;\n}\n\nfunction resolveTags(frontmatter: Frontmatter): string[] | undefined {\n const fm = frontmatter.tags;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string') return [fm];\n if (Array.isArray(fm)) return fm;\n throw new CliError('USAGE', 'frontmatter tags must be a list of strings.');\n}\n\nfunction expectString(frontmatter: Frontmatter, key: string): string | undefined {\n const fm = frontmatter[key];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', `frontmatter ${key} must be a single string.`);\n }\n return fm;\n}\n\nfunction resolvePrice(args: PublishArgs, frontmatter: Frontmatter, defaultAtomic: string): string {\n if (args.price !== undefined) return parseUsdToAtomic(args.price);\n const fm = frontmatter.price;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter price must be a decimal-USD string, e.g. \"0.10\".');\n }\n return parseUsdToAtomic(fm);\n }\n return defaultAtomic;\n}\n\nfunction cardFlagsFrom(args: PublishArgs): 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 derived card's free-text values as one newline-joined document, so the scan\n * covers card-flag input (which never touches the file) at the same severity as\n * the body. Empty when there is no card.\n */\nfunction cardScanText(card: ResourceCardInput | undefined): string {\n if (card === undefined) return '';\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n add(card.scope);\n add(card.exclusions);\n add(card.provenanceSummary);\n add(card.methodologySummary);\n add(card.mediaType);\n add(card.maintenanceCadence);\n add(card.asOf);\n add(card.validUntil);\n add(card.estimatedPaidInputCost);\n if (card.questionsAnswered !== undefined) parts.push(...card.questionsAnswered);\n if (card.tasksSupported !== undefined) parts.push(...card.tasksSupported);\n if (card.appliesTo !== undefined) {\n for (const values of Object.values(card.appliesTo)) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Finding + message shaping.\n// ---------------------------------------------------------------------------\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Publish blocked: the file contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, priceUsd: string): string {\n return warnCount > 0\n ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.`\n : `Publish needs confirmation: price $${priceUsd}.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA+FjC,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAIpC,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AACrE,QAAM,YAAY,mBAAmB,KAAK,UAAU,KAAK,iBAAiB,aAAa;AAEvF,QAAM,MAAM,MAAM,WAAW,IAAI;AAGjC,QAAM,SAAS,MAAM,kBAAkB,KAAK,SAAS;AACrD,QAAM,EAAE,aAAa,KAAK,IAAI,iBAAiB,GAAG;AAElD,QAAM,SAAS,cAAc,MAAM,WAAW;AAC9C,MAAI,WAAW,QAAS,gBAAe,KAAK,WAAW,MAAM;AAC7D,QAAM,QAAQ,aAAa,aAAa,IAAI;AAC5C,QAAM,OAAO,YAAY,WAAW;AACpC,QAAM,UAAU,eAAe,MAAM,WAAW;AAChD,QAAM,SAAS,aAAa,aAAa,QAAQ;AAIjD,QAAM,YAAY,cAAc,IAAI;AAEpC,QAAM,cAAc,UAAU,KAAK,CAAC,OAAO,OAAO,IAAI,EAAE,GAAG,aAAa,MAAS;AACjF,QAAM,SAAS,gBAAgB,SAAY,SAAY,OAAO,IAAI,WAAW,GAAG;AAChF,QAA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C,iBAAiB,QAAQ,CAAC;AACzE;AAEA,SAAS,eAAe,WAAmB,UAA0B;AACnE,SAAO,YAAY,IACf,+BAA+B,SAAS,uBAAuB,QAAQ,MACvE,sCAAsC,QAAQ;AACpD;","names":[]}
@@ -1,16 +1,19 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- findStoredCandidate
4
- } from "./chunk-7NADDA2V.js";
5
2
  import {
6
3
  SLUG_RE,
7
4
  UUID_RE
8
- } from "./chunk-736DW4V3.js";
5
+ } from "./chunk-EFWZPUTC.js";
6
+ import {
7
+ findStoredCandidate
8
+ } from "./chunk-A5DKHMUN.js";
9
+ import {
10
+ isSameDeployment
11
+ } from "./chunk-2MYQN7HM.js";
9
12
  import {
10
13
  CliError,
11
14
  external_exports,
12
15
  writeFileAtomic
13
- } from "./chunk-PAOVPSP6.js";
16
+ } from "./chunk-ZFJJ3EXC.js";
14
17
 
15
18
  // src/lib/library.ts
16
19
  import { createHash } from "crypto";
@@ -166,7 +169,7 @@ function assertOnBaseOrigin(url, baseUrl, what) {
166
169
  fix: "Pass an absolute https URL on the configured base URL."
167
170
  });
168
171
  }
169
- if (target.origin !== base.origin) {
172
+ if (!isSameDeployment(target.origin, base.origin)) {
170
173
  throw new CliError(
171
174
  "USAGE",
172
175
  `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,
@@ -210,4 +213,4 @@ export {
210
213
  assertOnBaseOrigin,
211
214
  resolveResourceRef
212
215
  };
213
- //# sourceMappingURL=chunk-4Y53PDH6.js.map
216
+ //# sourceMappingURL=chunk-VJQKL3YH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/library.ts","../src/lib/resource-ref.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Filesystem identity is server-controlled (the read body's id + slug), so it is\n * hostile input to a path. resourceId must be a uuid and slug must match the\n * server's slug charset (lib/posts.ts slugify: lowercase a-z0-9 groups joined by\n * single hyphens, no leading/trailing hyphen, <=80 chars). This is the primary\n * guard; assertContained is the defense-in-depth backstop.\n */\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/**\n * Local library delivery (spec 10): purchased or freely-read bodies are saved\n * under `<dataDir>/library/<resourceId>/<slug>.md` with a sidecar `receipt.json`\n * carrying the entitlement + payment identity. A `buy` on already-delivered\n * content re-delivers FROM DISK, the receipt is the local entitlement record, so\n * a repeat buy never re-pays and never re-fetches. `contentHash` is the sha256 the\n * outcome endpoint expects, computed over the exact saved bytes.\n */\n\nexport type Entitlement = 'free' | 'entitled' | 'purchased';\n\nexport const ReceiptSchema = z.object({\n schemaVersion: z.literal(1),\n resourceId: z.string(),\n slug: z.string(),\n title: z.string(),\n handle: z.string(),\n url: z.string(),\n priceAtomic: z.string(),\n entitlement: z.enum(['free', 'entitled', 'purchased']),\n contentHash: z.string(),\n settlementTxHash: z.string().optional(),\n savedAt: z.string(),\n});\nexport type Receipt = z.infer<typeof ReceiptSchema>;\n\nexport function libraryDir(dataDir: string): string {\n return join(dataDir, 'library');\n}\n\nexport function resourceDir(dataDir: string, resourceId: string): string {\n return join(libraryDir(dataDir), resourceId);\n}\n\n/** True when `resourceId` is a uuid and `slug` matches the server's slug charset,\n * so neither can carry a path separator or `..`. */\nexport function isSafeIdentity(resourceId: string, slug: string): boolean {\n return RESOURCE_ID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);\n}\n\n/**\n * Defense-in-depth: refuse a delivery whose identity is malformed OR whose\n * resolved write path escapes the library root. A malicious server returning\n * id='../../etc' or slug='../../evil' is rejected as a contract violation before\n * any bytes (or directories) are written.\n */\nfunction assertContained(dataDir: string, resourceId: string, slug: string): void {\n if (!isSafeIdentity(resourceId, slug)) {\n throw new CliError('CONTRACT_MISMATCH', 'The server returned an unsafe resource identity.', {\n fix: 'Update tenjin-cli or report the resource; the id/slug is not a valid identity.',\n details: { resourceId, slug },\n });\n }\n const root = resolve(libraryDir(dataDir));\n const target = resolve(bodyPath(dataDir, resourceId, slug));\n const rel = relative(root, target);\n if (rel.startsWith('..') || isAbsolute(rel) || rel.split(/[\\\\/]/).includes('..')) {\n throw new CliError('CONTRACT_MISMATCH', 'The delivery path escapes the library directory.', {\n fix: 'Update tenjin-cli; the resource identity is unsafe.',\n });\n }\n}\n\nexport function bodyPath(dataDir: string, resourceId: string, slug: string): string {\n return join(resourceDir(dataDir, resourceId), `${slug}.md`);\n}\n\nexport function receiptPath(dataDir: string, resourceId: string): string {\n return join(resourceDir(dataDir, resourceId), 'receipt.json');\n}\n\n/** sha256 over the UTF-8 bytes of `bodyMd`, \"sha256:<64 hex>\" (server contract). */\nexport function contentHash(bodyMd: string): string {\n return `sha256:${createHash('sha256').update(bodyMd, 'utf8').digest('hex')}`;\n}\n\nexport interface DeliveredResource {\n receipt: Receipt;\n bodyMd: string;\n bodyPath: string;\n}\n\n/** Return the on-disk delivery for a resource, or null when nothing is saved yet\n * (or the sidecar is unreadable/corrupt, treated as absent, never a hard error). */\nexport async function findDelivered(\n dataDir: string,\n resourceId: string,\n): Promise<DeliveredResource | null> {\n // A non-uuid resourceId can never have been a saved directory; treat it as\n // absent rather than probing an attacker-shaped path.\n if (!RESOURCE_ID_RE.test(resourceId)) return null;\n let receiptRaw: string;\n try {\n receiptRaw = await readFile(receiptPath(dataDir, resourceId), 'utf8');\n } catch {\n return null;\n }\n const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));\n if (!parsed.success) return null;\n const path = bodyPath(dataDir, resourceId, parsed.data.slug);\n let bodyMd: string;\n try {\n bodyMd = await readFile(path, 'utf8');\n } catch {\n return null;\n }\n return { receipt: parsed.data, bodyMd, bodyPath: path };\n}\n\n/**\n * The read route's path shape. The trailing slash is OPTIONAL here, which is a\n * deliberate tolerance: a URL a human pasted with one addresses the same piece.\n * `parseReadPath` and `canonicalReadUrl` share this regex so the shape they\n * tolerate and the shape one of them removes can never drift apart.\n */\nconst READ_PATH_RE = /\\/api\\/read\\/([^/]+)\\/([^/]+)\\/?$/;\n\n/** The (handle, slug) a read URL points at, path-only so base-url/trailing-slash\n * differences never matter. Null when the URL is not a read-route URL. */\nexport function parseReadPath(url: string): { handle: string; slug: string } | null {\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return null;\n }\n const m = READ_PATH_RE.exec(pathname);\n if (m === null || m[1] === undefined || m[2] === undefined) return null;\n return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };\n}\n\n/**\n * A read URL in the spelling the transport should ask for: the same URL with\n * `parseReadPath`'s optional trailing slash removed.\n *\n * This exists because the tolerance above and the transport disagree without it.\n * `fetchRead` pins `blockRedirects`, so a 3xx anywhere on the read path is a hard\n * failure rather than a hop — and the read route legitimately canonicalizes\n * `/api/read/<handle>/<slug>/` to the no-slash form. Left un-normalized, a URL a\n * user pasted with a trailing slash therefore dies at the FIRST probe of both\n * `read` and `buy`, on a redirect the pin is not there to catch: it is\n * same-origin, so no other host's bytes are in play.\n *\n * Removing the slash instead of relaxing the pin keeps the two concerns apart.\n * Canonicalizing a URL is this function's job; refusing to follow a redirect\n * stays the transport's, unconditionally.\n *\n * Path-only and conservative: a non-read URL is returned untouched, the query and\n * fragment are preserved byte-for-byte, and only the ONE slash the regex tolerates\n * is removed (so `/api/read/h/s//`, which `parseReadPath` already rejects, is left\n * exactly as it came in). It cannot change the origin, which is why callers may\n * origin-check the result rather than the input.\n */\nexport function canonicalReadUrl(url: string): string {\n if (parseReadPath(url) === null) return url;\n const mark = url.search(/[?#]/);\n const path = mark === -1 ? url : url.slice(0, mark);\n if (!path.endsWith('/')) return url;\n return path.slice(0, -1) + (mark === -1 ? '' : url.slice(mark));\n}\n\n/**\n * Find a delivered resource by its READ URL (handle/slug), for the double-pay\n * guard on a `buy <url>` where the resourceId isn't known up front. Scans the\n * library's receipts and matches on the URL's handle+slug path, so a repeat buy\n * of an owned resource re-delivers from disk before any network or payment.\n */\nexport async function findDeliveredByUrl(\n dataDir: string,\n url: string,\n): Promise<DeliveredResource | null> {\n const target = parseReadPath(url);\n if (target === null) return null;\n let entries: string[];\n try {\n entries = await readdir(libraryDir(dataDir));\n } catch {\n return null;\n }\n for (const resourceId of entries) {\n if (!RESOURCE_ID_RE.test(resourceId)) continue;\n const delivered = await findDelivered(dataDir, resourceId);\n if (delivered === null) continue;\n const saved = parseReadPath(delivered.receipt.url);\n if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {\n return delivered;\n }\n }\n return null;\n}\n\nexport interface SaveDeliveryInput {\n resourceId: string;\n slug: string;\n title: string;\n handle: string;\n url: string;\n priceAtomic: string;\n entitlement: Entitlement;\n bodyMd: string;\n settlementTxHash?: string;\n}\n\nexport interface SavedDelivery {\n receipt: Receipt;\n bodyPath: string;\n}\n\n/** Persist the body + receipt atomically. Idempotent by path: re-saving the same\n * resource overwrites the sidecar (e.g. a free read later becomes a purchase). */\nexport async function saveDelivery(\n dataDir: string,\n input: SaveDeliveryInput,\n): Promise<SavedDelivery> {\n assertContained(dataDir, input.resourceId, input.slug);\n const path = bodyPath(dataDir, input.resourceId, input.slug);\n const receipt: Receipt = {\n schemaVersion: 1,\n resourceId: input.resourceId,\n slug: input.slug,\n title: input.title,\n handle: input.handle,\n url: input.url,\n priceAtomic: input.priceAtomic,\n entitlement: input.entitlement,\n contentHash: contentHash(input.bodyMd),\n ...(input.settlementTxHash !== undefined ? { settlementTxHash: input.settlementTxHash } : {}),\n savedAt: new Date().toISOString(),\n };\n await writeFileAtomic(path, input.bodyMd, { mode: 0o644, dirMode: 0o700 });\n await writeFileAtomic(\n receiptPath(dataDir, input.resourceId),\n `${JSON.stringify(receipt, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n return { receipt, bodyPath: path };\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { CliError } from './errors';\nimport { findStoredCandidate } from './search-store';\nimport { canonicalReadUrl } from './library';\nimport { UUID_RE } from './ids';\n\n/**\n * Resolve a `<resource-url-or-id>` CLI argument to the payable read URL. A full\n * http(s) URL must live on the configured base URL's origin; a bare uuid is a\n * resourceId, resolved to its URL through the local search store (the read route\n * is keyed by handle/slug, so an id alone cannot build the URL). Anything else is\n * a usage error with a clear fix.\n *\n * The origin pin is a MONEY-PATH trust boundary, not pedantry: `buy` sends a\n * wallet-signed SIWX header (a bearer credential scoped to the configured\n * domain) and an EIP-3009 payment authorization to whatever host the resolved\n * URL names. An off-origin URL, whether typed by hand or planted in a search\n * candidate, would hand both to that host. Nothing signed may leave for a host\n * the user did not configure.\n *\n * This is also the one place a read URL is CANONICALIZED, because it is the one\n * place `read`, `buy`, and `inspect` all resolve through: a trailing slash is\n * removed (see `canonicalReadUrl`) so the URL that goes to the transport is the\n * spelling the read route serves without a redirect. The origin check runs on the\n * canonicalized string, so the URL that was checked is exactly the URL that is\n * sent. Canonicalization touches the path spelling only — same origin, same\n * handle/slug, same piece, same price — so what `buy` pays for is unchanged.\n */\n\nexport interface ResourceRef {\n url: string;\n resourceId?: string;\n}\n\n/** Throws USAGE unless `url` parses and shares the base URL's origin. */\nexport function assertOnBaseOrigin(url: string, baseUrl: string, what: string): void {\n let target: URL;\n let base: URL;\n try {\n target = new URL(url);\n base = new URL(baseUrl);\n } catch {\n throw new CliError('USAGE', `Invalid ${what}: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute https URL on the configured base URL.',\n });\n }\n if (target.origin !== base.origin) {\n throw new CliError(\n 'USAGE',\n `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,\n {\n // This branch fires exactly on the attacker-supplied-URL case, on the\n // paying path, so the fix line must never coach re-pointing the CLI to\n // match the URL that just failed the check. Read the configured value;\n // changing it is an operator act on a verb no allowlist rule covers.\n fix: 'The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`.',\n },\n );\n }\n}\n\nexport async function resolveResourceRef(\n arg: string,\n dataDir: string,\n baseUrl: string,\n): Promise<ResourceRef> {\n const trimmed = arg.trim();\n if (/^https?:\\/\\//i.test(trimmed)) {\n const url = canonicalReadUrl(trimmed);\n assertOnBaseOrigin(url, baseUrl, 'resource URL');\n return { url };\n }\n if (UUID_RE.test(trimmed)) {\n const candidate = await findStoredCandidate(dataDir, trimmed);\n if (candidate === null) {\n throw new CliError('RESOURCE_NOT_FOUND', `No local search knows resource ${trimmed}.`, {\n fix: 'Run `tenjin search` to surface it first, or pass the full read URL.',\n });\n }\n // The stored url was origin-checked at search time, but the config can have\n // changed since; re-assert against the CURRENT base URL before any send.\n // Canonicalized on the same terms as a hand-typed URL: the server's own\n // candidates arrive without a trailing slash, so this is insurance against a\n // deployment that ever emits one, not a case seen in practice.\n const url = canonicalReadUrl(candidate.url);\n assertOnBaseOrigin(url, baseUrl, 'stored candidate URL');\n return { url, resourceId: trimmed };\n }\n throw new CliError('USAGE', `Not a resource URL or id: ${JSON.stringify(arg)}`, {\n fix: 'Pass a full https read URL (a candidate `url`) or a resourceId uuid.',\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,eAAe;AAClC,SAAS,YAAY,MAAM,UAAU,eAAe;AAyB7C,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EACpC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,YAAY,iBAAE,OAAO;AAAA,EACrB,MAAM,iBAAE,OAAO;AAAA,EACf,OAAO,iBAAE,OAAO;AAAA,EAChB,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAAA,EACd,aAAa,iBAAE,OAAO;AAAA,EACtB,aAAa,iBAAE,KAAK,CAAC,QAAQ,YAA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H;","names":[]}
1
+ {"version":3,"sources":["../src/lib/library.ts","../src/lib/resource-ref.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Filesystem identity is server-controlled (the read body's id + slug), so it is\n * hostile input to a path. resourceId must be a uuid and slug must match the\n * server's slug charset (lib/posts.ts slugify: lowercase a-z0-9 groups joined by\n * single hyphens, no leading/trailing hyphen, <=80 chars). This is the primary\n * guard; assertContained is the defense-in-depth backstop.\n */\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/**\n * Local library delivery (spec 10): purchased or freely-read bodies are saved\n * under `<dataDir>/library/<resourceId>/<slug>.md` with a sidecar `receipt.json`\n * carrying the entitlement + payment identity. A `buy` on already-delivered\n * content re-delivers FROM DISK, the receipt is the local entitlement record, so\n * a repeat buy never re-pays and never re-fetches. `contentHash` is the sha256 the\n * outcome endpoint expects, computed over the exact saved bytes.\n */\n\nexport type Entitlement = 'free' | 'entitled' | 'purchased';\n\nexport const ReceiptSchema = z.object({\n schemaVersion: z.literal(1),\n resourceId: z.string(),\n slug: z.string(),\n title: z.string(),\n handle: z.string(),\n url: z.string(),\n priceAtomic: z.string(),\n entitlement: z.enum(['free', 'entitled', 'purchased']),\n contentHash: z.string(),\n settlementTxHash: z.string().optional(),\n savedAt: z.string(),\n});\nexport type Receipt = z.infer<typeof ReceiptSchema>;\n\nexport function libraryDir(dataDir: string): string {\n return join(dataDir, 'library');\n}\n\nexport function resourceDir(dataDir: string, resourceId: string): string {\n return join(libraryDir(dataDir), resourceId);\n}\n\n/** True when `resourceId` is a uuid and `slug` matches the server's slug charset,\n * so neither can carry a path separator or `..`. */\nexport function isSafeIdentity(resourceId: string, slug: string): boolean {\n return RESOURCE_ID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);\n}\n\n/**\n * Defense-in-depth: refuse a delivery whose identity is malformed OR whose\n * resolved write path escapes the library root. A malicious server returning\n * id='../../etc' or slug='../../evil' is rejected as a contract violation before\n * any bytes (or directories) are written.\n */\nfunction assertContained(dataDir: string, resourceId: string, slug: string): void {\n if (!isSafeIdentity(resourceId, slug)) {\n throw new CliError('CONTRACT_MISMATCH', 'The server returned an unsafe resource identity.', {\n fix: 'Update tenjin-cli or report the resource; the id/slug is not a valid identity.',\n details: { resourceId, slug },\n });\n }\n const root = resolve(libraryDir(dataDir));\n const target = resolve(bodyPath(dataDir, resourceId, slug));\n const rel = relative(root, target);\n if (rel.startsWith('..') || isAbsolute(rel) || rel.split(/[\\\\/]/).includes('..')) {\n throw new CliError('CONTRACT_MISMATCH', 'The delivery path escapes the library directory.', {\n fix: 'Update tenjin-cli; the resource identity is unsafe.',\n });\n }\n}\n\nexport function bodyPath(dataDir: string, resourceId: string, slug: string): string {\n return join(resourceDir(dataDir, resourceId), `${slug}.md`);\n}\n\nexport function receiptPath(dataDir: string, resourceId: string): string {\n return join(resourceDir(dataDir, resourceId), 'receipt.json');\n}\n\n/** sha256 over the UTF-8 bytes of `bodyMd`, \"sha256:<64 hex>\" (server contract). */\nexport function contentHash(bodyMd: string): string {\n return `sha256:${createHash('sha256').update(bodyMd, 'utf8').digest('hex')}`;\n}\n\nexport interface DeliveredResource {\n receipt: Receipt;\n bodyMd: string;\n bodyPath: string;\n}\n\n/** Return the on-disk delivery for a resource, or null when nothing is saved yet\n * (or the sidecar is unreadable/corrupt, treated as absent, never a hard error). */\nexport async function findDelivered(\n dataDir: string,\n resourceId: string,\n): Promise<DeliveredResource | null> {\n // A non-uuid resourceId can never have been a saved directory; treat it as\n // absent rather than probing an attacker-shaped path.\n if (!RESOURCE_ID_RE.test(resourceId)) return null;\n let receiptRaw: string;\n try {\n receiptRaw = await readFile(receiptPath(dataDir, resourceId), 'utf8');\n } catch {\n return null;\n }\n const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));\n if (!parsed.success) return null;\n const path = bodyPath(dataDir, resourceId, parsed.data.slug);\n let bodyMd: string;\n try {\n bodyMd = await readFile(path, 'utf8');\n } catch {\n return null;\n }\n return { receipt: parsed.data, bodyMd, bodyPath: path };\n}\n\n/**\n * The read route's path shape. The trailing slash is OPTIONAL here, which is a\n * deliberate tolerance: a URL a human pasted with one addresses the same piece.\n * `parseReadPath` and `canonicalReadUrl` share this regex so the shape they\n * tolerate and the shape one of them removes can never drift apart.\n */\nconst READ_PATH_RE = /\\/api\\/read\\/([^/]+)\\/([^/]+)\\/?$/;\n\n/** The (handle, slug) a read URL points at, path-only so base-url/trailing-slash\n * differences never matter. Null when the URL is not a read-route URL. */\nexport function parseReadPath(url: string): { handle: string; slug: string } | null {\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return null;\n }\n const m = READ_PATH_RE.exec(pathname);\n if (m === null || m[1] === undefined || m[2] === undefined) return null;\n return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };\n}\n\n/**\n * A read URL in the spelling the transport should ask for: the same URL with\n * `parseReadPath`'s optional trailing slash removed.\n *\n * This exists because the tolerance above and the transport disagree without it.\n * `fetchRead` pins `blockRedirects`, so a 3xx anywhere on the read path is a hard\n * failure rather than a hop — and the read route legitimately canonicalizes\n * `/api/read/<handle>/<slug>/` to the no-slash form. Left un-normalized, a URL a\n * user pasted with a trailing slash therefore dies at the FIRST probe of both\n * `read` and `buy`, on a redirect the pin is not there to catch: it is\n * same-origin, so no other host's bytes are in play.\n *\n * Removing the slash instead of relaxing the pin keeps the two concerns apart.\n * Canonicalizing a URL is this function's job; refusing to follow a redirect\n * stays the transport's, unconditionally.\n *\n * Path-only and conservative: a non-read URL is returned untouched, the query and\n * fragment are preserved byte-for-byte, and only the ONE slash the regex tolerates\n * is removed (so `/api/read/h/s//`, which `parseReadPath` already rejects, is left\n * exactly as it came in). It cannot change the origin, which is why callers may\n * origin-check the result rather than the input.\n */\nexport function canonicalReadUrl(url: string): string {\n if (parseReadPath(url) === null) return url;\n const mark = url.search(/[?#]/);\n const path = mark === -1 ? url : url.slice(0, mark);\n if (!path.endsWith('/')) return url;\n return path.slice(0, -1) + (mark === -1 ? '' : url.slice(mark));\n}\n\n/**\n * Find a delivered resource by its READ URL (handle/slug), for the double-pay\n * guard on a `buy <url>` where the resourceId isn't known up front. Scans the\n * library's receipts and matches on the URL's handle+slug path, so a repeat buy\n * of an owned resource re-delivers from disk before any network or payment.\n */\nexport async function findDeliveredByUrl(\n dataDir: string,\n url: string,\n): Promise<DeliveredResource | null> {\n const target = parseReadPath(url);\n if (target === null) return null;\n let entries: string[];\n try {\n entries = await readdir(libraryDir(dataDir));\n } catch {\n return null;\n }\n for (const resourceId of entries) {\n if (!RESOURCE_ID_RE.test(resourceId)) continue;\n const delivered = await findDelivered(dataDir, resourceId);\n if (delivered === null) continue;\n const saved = parseReadPath(delivered.receipt.url);\n if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {\n return delivered;\n }\n }\n return null;\n}\n\nexport interface SaveDeliveryInput {\n resourceId: string;\n slug: string;\n title: string;\n handle: string;\n url: string;\n priceAtomic: string;\n entitlement: Entitlement;\n bodyMd: string;\n settlementTxHash?: string;\n}\n\nexport interface SavedDelivery {\n receipt: Receipt;\n bodyPath: string;\n}\n\n/** Persist the body + receipt atomically. Idempotent by path: re-saving the same\n * resource overwrites the sidecar (e.g. a free read later becomes a purchase). */\nexport async function saveDelivery(\n dataDir: string,\n input: SaveDeliveryInput,\n): Promise<SavedDelivery> {\n assertContained(dataDir, input.resourceId, input.slug);\n const path = bodyPath(dataDir, input.resourceId, input.slug);\n const receipt: Receipt = {\n schemaVersion: 1,\n resourceId: input.resourceId,\n slug: input.slug,\n title: input.title,\n handle: input.handle,\n url: input.url,\n priceAtomic: input.priceAtomic,\n entitlement: input.entitlement,\n contentHash: contentHash(input.bodyMd),\n ...(input.settlementTxHash !== undefined ? { settlementTxHash: input.settlementTxHash } : {}),\n savedAt: new Date().toISOString(),\n };\n await writeFileAtomic(path, input.bodyMd, { mode: 0o644, dirMode: 0o700 });\n await writeFileAtomic(\n receiptPath(dataDir, input.resourceId),\n `${JSON.stringify(receipt, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n return { receipt, bodyPath: path };\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { CliError } from './errors';\nimport { findStoredCandidate } from './search-store';\nimport { canonicalReadUrl } from './library';\nimport { UUID_RE } from './ids';\nimport { isSameDeployment } from './production-origin';\n\n/**\n * Resolve a `<resource-url-or-id>` CLI argument to the payable read URL. A full\n * http(s) URL must live on the configured deployment; a bare uuid is a\n * resourceId, resolved to its URL through the local search store (the read route\n * is keyed by handle/slug, so an id alone cannot build the URL). Anything else is\n * a usage error with a clear fix.\n *\n * The origin pin is a MONEY-PATH trust boundary, not pedantry: `buy` sends a\n * wallet-signed SIWX header (a bearer credential scoped to the configured\n * domain) and an EIP-3009 payment authorization to whatever host the resolved\n * URL names. An off-origin URL, whether typed by hand or planted in a search\n * candidate, would hand both to that host. Nothing signed may leave for a\n * deployment the user did not configure: `isSameDeployment` widens \"origin\" to\n * the alias set of the one deployment the base already names, never past it.\n *\n * This is also the one place a read URL is CANONICALIZED, because it is the one\n * place `read`, `buy`, and `inspect` all resolve through: a trailing slash is\n * removed (see `canonicalReadUrl`) so the URL that goes to the transport is the\n * spelling the read route serves without a redirect. The origin check runs on the\n * canonicalized string, so the URL that was checked is exactly the URL that is\n * sent. Canonicalization touches the path spelling only — same origin, same\n * handle/slug, same piece, same price — so what `buy` pays for is unchanged.\n */\n\nexport interface ResourceRef {\n url: string;\n resourceId?: string;\n}\n\n/**\n * Throws USAGE unless `url` parses and shares the base URL's origin, or names\n * the same deployment under `isSameDeployment` — which is the SAME server, not a\n * second one the CLI now trusts. Aliasing applies only when the configured base\n * is one of the deployment's own origins; a self-hosted base keeps the exact\n * compare, and every other origin is refused on the terms it always was.\n */\nexport function assertOnBaseOrigin(url: string, baseUrl: string, what: string): void {\n let target: URL;\n let base: URL;\n try {\n target = new URL(url);\n base = new URL(baseUrl);\n } catch {\n throw new CliError('USAGE', `Invalid ${what}: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute https URL on the configured base URL.',\n });\n }\n if (!isSameDeployment(target.origin, base.origin)) {\n throw new CliError(\n 'USAGE',\n `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,\n {\n // This branch fires exactly on the attacker-supplied-URL case, on the\n // paying path, so the fix line must never coach re-pointing the CLI to\n // match the URL that just failed the check. Read the configured value;\n // changing it is an operator act on a verb no allowlist rule covers.\n fix: 'The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`.',\n },\n );\n }\n}\n\nexport async function resolveResourceRef(\n arg: string,\n dataDir: string,\n baseUrl: string,\n): Promise<ResourceRef> {\n const trimmed = arg.trim();\n if (/^https?:\\/\\//i.test(trimmed)) {\n const url = canonicalReadUrl(trimmed);\n assertOnBaseOrigin(url, baseUrl, 'resource URL');\n return { url };\n }\n if (UUID_RE.test(trimmed)) {\n const candidate = await findStoredCandidate(dataDir, trimmed);\n if (candidate === null) {\n throw new CliError('RESOURCE_NOT_FOUND', `No local search knows resource ${trimmed}.`, {\n fix: 'Run `tenjin search` to surface it first, or pass the full read URL.',\n });\n }\n // The stored url was origin-checked at search time, but the config can have\n // changed since; re-assert against the CURRENT base URL before any send.\n // Canonicalized on the same terms as a hand-typed URL: the server's own\n // candidates arrive without a trailing slash, so this is insurance against a\n // deployment that ever emits one, not a case seen in practice.\n const url = canonicalReadUrl(candidate.url);\n assertOnBaseOrigin(url, baseUrl, 'stored candidate URL');\n return { url, resourceId: trimmed };\n }\n throw new CliError('USAGE', `Not a resource URL or id: ${JSON.stringify(arg)}`, {\n fix: 'Pass a full https read URL (a candidate `url`) or a resourceId uuid.',\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,IAAI;AAAA,EACf;AACA,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,UAAM,YAAY,MAAM,oBAAoB,SAAS,OAAO;AAC5D,QAAI,cAAc,MAAM;AACtB,YAAM,IAAI,SAAS,sBAAsB,kCAAkC,OAAO,KAAK;AAAA,QACrF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAMA,UAAM,MAAM,iBAAiB,UAAU,GAAG;AAC1C,uBAAmB,KAAK,SAAS,sBAAsB;AACvD,WAAO,EAAE,KAAK,YAAY,QAAQ;AAAA,EACpC;AACA,QAAM,IAAI,SAAS,SAAS,6BAA6B,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,IAC9E,KAAK;AAAA,EACP,CAAC;AACH;","names":[]}
@@ -3,30 +3,30 @@ import {
3
3
  SESSION_CHAIN_ID,
4
4
  createSessionKeyAuth,
5
5
  createSiwxAuth
6
- } from "./chunk-WU5CZPLD.js";
6
+ } from "./chunk-QQ6ELLSA.js";
7
7
  import {
8
8
  rateLimitError
9
- } from "./chunk-FDUD3W5V.js";
10
- import {
11
- httpRequest
12
- } from "./chunk-54AJIO3E.js";
9
+ } from "./chunk-ITUXPJIS.js";
13
10
  import {
14
11
  trimSlash
15
- } from "./chunk-XGZ5EVMB.js";
12
+ } from "./chunk-EDZSNPE5.js";
13
+ import {
14
+ httpRequest
15
+ } from "./chunk-5QQTYWEU.js";
16
16
  import {
17
17
  sanitizeWireText
18
- } from "./chunk-B676GPS2.js";
18
+ } from "./chunk-OLWTRUTS.js";
19
19
  import {
20
20
  ATOMIC_RE,
21
21
  UUID_RE
22
- } from "./chunk-736DW4V3.js";
22
+ } from "./chunk-EFWZPUTC.js";
23
23
  import {
24
24
  PublishModeSchema
25
- } from "./chunk-LSWP7MU2.js";
25
+ } from "./chunk-U6VPKMGC.js";
26
26
  import {
27
27
  CliError,
28
28
  external_exports
29
- } from "./chunk-PAOVPSP6.js";
29
+ } from "./chunk-ZFJJ3EXC.js";
30
30
 
31
31
  // src/lib/scan.ts
32
32
  var LONG_QUOTE_WORDS = 80;
@@ -922,6 +922,33 @@ var PUBLISH_STATUSES = ["draft", "published", "unlisted"];
922
922
  var PRICE_RE = /^(0|[1-9]\d{0,12})$/;
923
923
  var HANDLE_RE = /^[a-z0-9-]{2,32}$/;
924
924
  var SEARCH_ID_WIRE_RE = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
925
+ var SEARCH_ID_MAX = 10;
926
+ function normalizeSearchIds(searchId, label) {
927
+ if (searchId === void 0) return [];
928
+ const given = typeof searchId === "string" ? [searchId] : searchId;
929
+ const ids = [...new Set(given.map((id) => id.toLowerCase()))];
930
+ for (const id of ids) {
931
+ if (!SEARCH_ID_WIRE_RE.test(id)) {
932
+ throw new CliError("USAGE", `Invalid ${label}: ${JSON.stringify(id)}`, {
933
+ fix: "Pass the searchId from a prior `tenjin search` (a uuid)."
934
+ });
935
+ }
936
+ }
937
+ if (ids.length > SEARCH_ID_MAX) {
938
+ throw new CliError(
939
+ "USAGE",
940
+ `One piece claims at most ${SEARCH_ID_MAX} searches (got ${ids.length}).`,
941
+ {
942
+ fix: `Name the ${SEARCH_ID_MAX} this piece actually answers, then close the rest with \`tenjin outcome --search-id <id> --status regenerated\`.`
943
+ }
944
+ );
945
+ }
946
+ return ids;
947
+ }
948
+ function toWireSearchId(ids) {
949
+ if (ids.length === 0) return void 0;
950
+ return ids.length === 1 ? ids[0] : ids;
951
+ }
925
952
  var EXCERPT_MAX_LENGTH = 500;
926
953
  var RESERVED_HANDLES = /* @__PURE__ */ new Set(["latest"]);
927
954
  function sanitizeCard(card) {
@@ -1013,11 +1040,7 @@ function buildPostCreateBody(input) {
1013
1040
  });
1014
1041
  }
1015
1042
  }
1016
- if (input.searchId !== void 0 && !SEARCH_ID_WIRE_RE.test(input.searchId)) {
1017
- throw new CliError("USAGE", `Invalid searchId: ${JSON.stringify(input.searchId)}`, {
1018
- fix: "Pass the searchId from a prior `tenjin search` (a uuid)."
1019
- });
1020
- }
1043
+ const searchId = toWireSearchId(normalizeSearchIds(input.searchId, "searchId"));
1021
1044
  return {
1022
1045
  ...title !== void 0 && title.length > 0 ? { title } : {},
1023
1046
  ...bodyMd !== void 0 ? { bodyMd } : {},
@@ -1030,7 +1053,7 @@ function buildPostCreateBody(input) {
1030
1053
  // Sent whatever the LOCAL loop says, including on a relink and on a draft:
1031
1054
  // the server stores it against this post, and whether some earlier `outcome`
1032
1055
  // already reported on the search is not a fact about who answered it.
1033
- ...input.searchId !== void 0 ? { searchId: input.searchId } : {}
1056
+ ...searchId !== void 0 ? { searchId } : {}
1034
1057
  };
1035
1058
  }
1036
1059
  var resourceEchoSchema = external_exports.object({
@@ -1328,14 +1351,12 @@ function authError(code, res) {
1328
1351
  );
1329
1352
  }
1330
1353
  function publishFailed(res) {
1331
- return new CliError(
1332
- "PUBLISH_FAILED",
1333
- serverMessage(res.json) ?? `Publish failed (${res.status}).`,
1334
- {
1335
- fix: "Review the server error, then re-run `tenjin publish`.",
1336
- details: { status: res.status, ...res.json !== void 0 ? { server: res.json } : {} }
1337
- }
1338
- );
1354
+ const message = serverMessage(res.json);
1355
+ const rollout = res.status === 400 && message !== void 0 && /searchid/i.test(message);
1356
+ return new CliError("PUBLISH_FAILED", message ?? `Publish failed (${res.status}).`, {
1357
+ fix: rollout ? "Review the server error, then re-run `tenjin publish`. Naming several --search-id values needs a deployment whose post-create accepts an array; against an older one, publish with a single id." : "Review the server error, then re-run `tenjin publish`.",
1358
+ details: { status: res.status, ...res.json !== void 0 ? { server: res.json } : {} }
1359
+ });
1339
1360
  }
1340
1361
  function writeTransportError(url, result) {
1341
1362
  const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
@@ -1405,7 +1426,7 @@ export {
1405
1426
  missingSentences,
1406
1427
  localCardEligibility,
1407
1428
  PUBLISH_STATUSES,
1408
- SEARCH_ID_WIRE_RE,
1429
+ normalizeSearchIds,
1409
1430
  EXCERPT_MAX_LENGTH,
1410
1431
  publishPost,
1411
1432
  buildPostUpdateBody,
@@ -1418,4 +1439,4 @@ export {
1418
1439
  dedupeFindings,
1419
1440
  describeFindings
1420
1441
  };
1421
- //# sourceMappingURL=chunk-VRPLZERE.js.map
1442
+ //# sourceMappingURL=chunk-VJSQSLBM.js.map