tenjin-cli 0.1.0-alpha.5 → 0.1.0-alpha.8

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 (121) hide show
  1. package/README.md +169 -199
  2. package/dist/{buy-YMXXVNFH.js → buy-K2G6XQY2.js} +20 -18
  3. package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
  5. package/dist/{chunk-4WVKXKDK.js → chunk-6OE2IJMH.js} +29 -238
  6. package/dist/chunk-6OE2IJMH.js.map +1 -0
  7. package/dist/{chunk-ADJYSM45.js → chunk-6ZBZCBR7.js} +27 -13
  8. package/dist/chunk-6ZBZCBR7.js.map +1 -0
  9. package/dist/{chunk-HTDALK7M.js → chunk-B7YB4MMU.js} +15 -12
  10. package/dist/{chunk-HTDALK7M.js.map → chunk-B7YB4MMU.js.map} +1 -1
  11. package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
  12. package/dist/chunk-BBUYCDSG.js.map +1 -0
  13. package/dist/chunk-C3S6725N.js +337 -0
  14. package/dist/chunk-C3S6725N.js.map +1 -0
  15. package/dist/chunk-CYRYVZPN.js +213 -0
  16. package/dist/chunk-CYRYVZPN.js.map +1 -0
  17. package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
  18. package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
  19. package/dist/{chunk-NJF2WENW.js → chunk-DQDGBWWH.js} +4 -2
  20. package/dist/chunk-DQDGBWWH.js.map +1 -0
  21. package/dist/chunk-EDENZN2Q.js +614 -0
  22. package/dist/chunk-EDENZN2Q.js.map +1 -0
  23. package/dist/chunk-GABYDXWL.js +190 -0
  24. package/dist/chunk-GABYDXWL.js.map +1 -0
  25. package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
  26. package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
  27. package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
  28. package/dist/chunk-J6CVKC4M.js.map +1 -0
  29. package/dist/chunk-L6AV2Q73.js +105 -0
  30. package/dist/chunk-L6AV2Q73.js.map +1 -0
  31. package/dist/{chunk-PYNSGYBE.js → chunk-NVHQCTIC.js} +249 -552
  32. package/dist/chunk-NVHQCTIC.js.map +1 -0
  33. package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
  34. package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
  35. package/dist/{chunk-3IRDP7TN.js → chunk-P3FBESBB.js} +6 -4
  36. package/dist/{chunk-3IRDP7TN.js.map → chunk-P3FBESBB.js.map} +1 -1
  37. package/dist/{chunk-FU6MCSLG.js → chunk-PCLPVJ3J.js} +16 -78
  38. package/dist/chunk-PCLPVJ3J.js.map +1 -0
  39. package/dist/chunk-QB2NNV6C.js +143 -0
  40. package/dist/chunk-QB2NNV6C.js.map +1 -0
  41. package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
  42. package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
  43. package/dist/{chunk-TXPPMK4L.js → chunk-RGTTACP3.js} +5 -5
  44. package/dist/chunk-SGK2B724.js +67 -0
  45. package/dist/chunk-SGK2B724.js.map +1 -0
  46. package/dist/{chunk-ZDY2KY5X.js → chunk-URSGGRO4.js} +28 -11
  47. package/dist/chunk-URSGGRO4.js.map +1 -0
  48. package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
  49. package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
  50. package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  51. package/dist/{chunk-QONTBYQW.js → chunk-WRWCDLVK.js} +4 -6
  52. package/dist/{chunk-QONTBYQW.js.map → chunk-WRWCDLVK.js.map} +1 -1
  53. package/dist/chunk-XBJ3VLWX.js +35 -0
  54. package/dist/chunk-XBJ3VLWX.js.map +1 -0
  55. package/dist/{chunk-RTJLLPFA.js → chunk-XFHZWORF.js} +123 -24
  56. package/dist/chunk-XFHZWORF.js.map +1 -0
  57. package/dist/{chunk-BIKAUVC2.js → chunk-ZA3RFDAV.js} +40 -6
  58. package/dist/chunk-ZA3RFDAV.js.map +1 -0
  59. package/dist/{cli-IW76QTN3.js → cli-KNCYWMAG.js} +237 -25
  60. package/dist/cli-KNCYWMAG.js.map +1 -0
  61. package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
  62. package/dist/dist-U4M6QCKE.js +2842 -0
  63. package/dist/dist-U4M6QCKE.js.map +1 -0
  64. package/dist/{doctor-WS65JG3V.js → doctor-FBRQNOUQ.js} +10 -9
  65. package/dist/{publish-DSFWQRUN.js → edit-IZZ2HIMR.js} +20 -18
  66. package/dist/index.js +1 -1
  67. package/dist/{inspect-SFJWUQHO.js → inspect-BFWZ5XOP.js} +17 -16
  68. package/dist/{install-RVPQPCKH.js → install-QXZCHIBT.js} +400 -166
  69. package/dist/install-QXZCHIBT.js.map +1 -0
  70. package/dist/outcome-VXCBEGNC.js +20 -0
  71. package/dist/publish-5NTCRF2V.js +40 -0
  72. package/dist/read-T6OTMU72.js +158 -0
  73. package/dist/read-T6OTMU72.js.map +1 -0
  74. package/dist/{run-OMPKA43G.js → run-5OGX64IY.js} +106 -32
  75. package/dist/{run-OMPKA43G.js.map → run-5OGX64IY.js.map} +1 -1
  76. package/dist/search-LIIWUMWV.js +24 -0
  77. package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
  78. package/dist/session-HY4QIWHV.js +87 -0
  79. package/dist/session-HY4QIWHV.js.map +1 -0
  80. package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
  81. package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
  82. package/dist/wallet-RBDVNZVR.js.map +1 -0
  83. package/docs/agent-permissions.md +255 -0
  84. package/package.json +3 -1
  85. package/skills/tenjin/SKILL.md +57 -13
  86. package/skills/tenjin-publish/SKILL.md +12 -4
  87. package/skills/tenjin-search/SKILL.md +68 -12
  88. package/dist/chunk-2JQ5JSG6.js +0 -68
  89. package/dist/chunk-2JQ5JSG6.js.map +0 -1
  90. package/dist/chunk-4WVKXKDK.js.map +0 -1
  91. package/dist/chunk-ADJYSM45.js.map +0 -1
  92. package/dist/chunk-BIKAUVC2.js.map +0 -1
  93. package/dist/chunk-FU6MCSLG.js.map +0 -1
  94. package/dist/chunk-L4IHCN6B.js +0 -63
  95. package/dist/chunk-L4IHCN6B.js.map +0 -1
  96. package/dist/chunk-NFSOVL3C.js.map +0 -1
  97. package/dist/chunk-NJF2WENW.js.map +0 -1
  98. package/dist/chunk-PAUXMRSF.js.map +0 -1
  99. package/dist/chunk-PYNSGYBE.js.map +0 -1
  100. package/dist/chunk-RTJLLPFA.js.map +0 -1
  101. package/dist/chunk-ZDY2KY5X.js.map +0 -1
  102. package/dist/cli-IW76QTN3.js.map +0 -1
  103. package/dist/install-RVPQPCKH.js.map +0 -1
  104. package/dist/outcome-GNYCSZ7J.js +0 -20
  105. package/dist/search-KOI6Y7P6.js +0 -24
  106. /package/dist/{buy-YMXXVNFH.js.map → buy-K2G6XQY2.js.map} +0 -0
  107. /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
  108. /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
  109. /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
  110. /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
  111. /package/dist/{chunk-TXPPMK4L.js.map → chunk-RGTTACP3.js.map} +0 -0
  112. /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
  113. /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
  114. /package/dist/{doctor-WS65JG3V.js.map → doctor-FBRQNOUQ.js.map} +0 -0
  115. /package/dist/{inspect-SFJWUQHO.js.map → edit-IZZ2HIMR.js.map} +0 -0
  116. /package/dist/{outcome-GNYCSZ7J.js.map → inspect-BFWZ5XOP.js.map} +0 -0
  117. /package/dist/{publish-DSFWQRUN.js.map → outcome-VXCBEGNC.js.map} +0 -0
  118. /package/dist/{search-KOI6Y7P6.js.map → publish-5NTCRF2V.js.map} +0 -0
  119. /package/dist/{wallet-B7KJS2R5.js.map → search-LIIWUMWV.js.map} +0 -0
  120. /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
  121. /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/scan.ts","../src/lib/scan-context.ts","../src/lib/card.ts","../src/lib/posts-api.ts","../src/lib/consent.ts"],"sourcesContent":["/**\n * The deterministic, offline redaction/rights scan (B3, Q14). Pure: identical\n * input yields an identical `findings[]`, no network and no model call. It runs\n * in every publish mode — it gates the explicit-approval gate, it does not\n * replace it. `block` findings refuse a publish in every mode and are never\n * `--yes`-clearable; `warn` findings are surfaced for review.\n *\n * A `block` excerpt is ALWAYS masked: the matched secret is never echoed\n * verbatim, only a short type-identifying prefix plus a redaction. `warn`\n * excerpts (wallet addresses, PII, quotes) show the caller their own content.\n *\n * The provider token-shape patterns (AWS, GitHub, Slack, Stripe, JWT, PEM) are\n * adapted from the gitleaks ruleset (MIT); the EVM raw-key (0x + 64 hex) and\n * wallet-address checks continue the BlockRun-credited wallet-key leak scanner.\n * Both are attributed in NOTICE.md. No pattern set is vendored as a dependency —\n * this is a wallet-holding CLI, kept offline with a tight dep tree by design.\n */\n\nexport type ScanSeverity = 'block' | 'warn';\n\nexport interface ScanFinding {\n /** Stable machine id for the detector, e.g. \"aws-access-key\". */\n check: string;\n severity: ScanSeverity;\n /** 1-based line number of the match (its start line, for multi-line matches). */\n line: number;\n /** [startColumn, endColumn) within `line`, 0-based (the start line for spans). */\n span: [number, number];\n /** Human-readable snippet; masked for every `block` finding. */\n excerpt: string;\n}\n\n/**\n * Optional caller-supplied context. The scan stays a pure function — of the text\n * AND the context — with zero model calls; the context only carries deterministic\n * facts the caller already holds (the source project's git remote slugs/paths at\n * publish time, per the open-questions publishing-safety check-set).\n */\nexport interface ScanContext {\n /**\n * Source-project identifiers treated as private-by-default: git remote\n * `org/repo` slugs and project paths. Matched case-insensitively as literal\n * substrings; a mention in the draft warns (the project may be public — the\n * offline scan cannot know — so this is ambiguity-class, never block).\n */\n projectMarkers?: string[];\n}\n\n/** Contiguous quoted/fenced runs at or above this word count read as copied. */\nconst LONG_QUOTE_WORDS = 80;\n\nexport function scan(text: string, context: ScanContext = {}): ScanFinding[] {\n const lines = text.split('\\n');\n const findings: ScanFinding[] = [\n ...scanHex64(lines),\n ...scanLineDetectors(lines),\n ...scanPemBlocks(lines),\n ...scanLongVerbatim(lines),\n ...scanProjectMarkers(lines, context.projectMarkers ?? []),\n ];\n return dedupeAndSort(suppressEmailsInDbUris(findings));\n}\n\n/**\n * Occurrences of the caller's private project markers (git remote slugs, paths)\n * in the text — warn 'private-repo-reference'. Literal case-insensitive match,\n * compiled once per marker (not per line) and executed against the ORIGINAL\n * line, so spans stay exact (a locale-sensitive toLowerCase can change string\n * length — U+0130 — and misalign them; review r5). Token-bounded: `Org/repo`\n * must not fire inside a sibling slug (`Org/repo-docs`, `xOrg/repo`), but a\n * trailing `.` stays allowed so a remote-URL mention (`…/Org/repo.git`) fires.\n * Markers shorter than 3 chars are dropped as degenerate. The excerpt names the\n * matched marker: it is the publisher's own project name, shown locally so they\n * can find and generalize the reference, not key material.\n */\nfunction scanProjectMarkers(lines: string[], markers: string[]): ScanFinding[] {\n const cleaned = [...new Set(markers.filter((m) => m.trim().length >= 3))];\n if (cleaned.length === 0) return [];\n const needles = cleaned.map((marker) => ({\n marker,\n re: new RegExp(`(?<![A-Za-z0-9._-])${escapeRegExp(marker)}(?![A-Za-z0-9_-])`, 'gi'),\n }));\n const out: ScanFinding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n for (const { marker, re } of needles) {\n re.lastIndex = 0;\n let m: RegExpExecArray | null;\n // Markers are >=3 chars, so every match advances lastIndex — no zero-width guard.\n while ((m = re.exec(line)) !== null) {\n out.push({\n check: 'private-repo-reference',\n severity: 'warn',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: marker,\n });\n }\n }\n }\n return out;\n}\n\n/** Escape a literal string for embedding in a RegExp source. */\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// A home-path username that is a docs placeholder, not a real machine username.\nconst PLACEHOLDER_USERNAME = /^(?:user(?:name)?|you(?:rname)?|example|foo|me|myuser|somebody)$/i;\n\n/**\n * A db-connection-uri already masks the embedded password; the email detector,\n * however, would match `password@host` and echo the password verbatim in its\n * excerpt. Drop any email finding whose span sits inside a db-connection-uri\n * span on the same line so the masking cannot be bypassed.\n */\nfunction suppressEmailsInDbUris(findings: ScanFinding[]): ScanFinding[] {\n const uris = findings.filter((f) => f.check === 'db-connection-uri');\n if (uris.length === 0) return findings;\n return findings.filter(\n (f) =>\n f.check !== 'email' ||\n !uris.some((u) => u.line === f.line && f.span[0] >= u.span[0] && f.span[1] <= u.span[1]),\n );\n}\n\n/**\n * Never echo more than a short, non-secret prefix. The kept prefix is a public\n * type marker (`0x`, `AKIA`, `ghp_`, …), never key material; the rest is dropped.\n */\nfunction maskKeeping(match: string, prefixLen: number): string {\n const prefix = match.slice(0, Math.min(prefixLen, match.length));\n return `${prefix}…[redacted ${match.length - prefix.length} chars]`;\n}\n\ninterface LineDetector {\n check: string;\n severity: ScanSeverity;\n /** Global regex; `lastIndex` is reset per line. */\n re: RegExp;\n /** Build the (possibly masked) excerpt from a single match. */\n excerpt: (m: RegExpExecArray) => string;\n /** Drop this match without a finding (e.g. a placeholder value). */\n skip?: (m: RegExpExecArray) => boolean;\n}\n\nconst LINE_DETECTORS: LineDetector[] = [\n // Secrets/keys — severity block, excerpt always masked. Provider patterns\n // adapted from gitleaks (MIT). The 0x-64-hex EVM key is handled separately\n // (scanHex64) so a tx/block hash is not hard-blocked. See header + NOTICE.md.\n {\n check: 'aws-access-key',\n severity: 'block',\n // gitleaks aws-access-token.\n re: /\\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 4),\n },\n {\n check: 'jwt',\n severity: 'block',\n // gitleaks jwt (three base64url segments, header starts eyJ).\n re: /\\beyJ[A-Za-z0-9_-]{5,}\\.eyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 3),\n },\n {\n check: 'github-token',\n severity: 'block',\n // gitleaks github-pat / -oauth / -app / -refresh (36 chars) + fine-grained pat.\n re: /\\b(?:gh[posru]_[0-9A-Za-z]{36}|github_pat_[0-9A-Za-z_]{82})\\b/g,\n excerpt: (m) => maskKeeping(m[0], 4),\n },\n {\n check: 'slack-token',\n severity: 'block',\n // gitleaks slack tokens (bot/user/app/refresh/legacy prefixes).\n re: /\\bxox[baprs]-[0-9A-Za-z-]{10,}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 5),\n },\n {\n check: 'stripe-token',\n severity: 'block',\n // gitleaks stripe-access-token.\n re: /\\b[sr]k_(?:live|test)_[0-9A-Za-z]{10,99}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 8),\n },\n {\n check: 'anthropic-key',\n severity: 'block',\n // gitleaks anthropic-api-key. Ordered before openai so sk-ant- isn't\n // mis-typed as a bare OpenAI sk- key.\n re: /\\bsk-ant-[0-9A-Za-z_-]{20,}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 7),\n },\n {\n check: 'openai-key',\n severity: 'block',\n // gitleaks openai-api-key: classic sk- plus the modern sk-proj-/sk-svcacct-/\n // sk-admin- keys. The body is base62 and MUST contain a digit (real keys are\n // high-entropy), which keeps sk- kebab identifiers (sk-user-profile-updated…)\n // from hard-blocking. `(?!ant-)` keeps an Anthropic key out. Only the base62\n // leading run of a modern key is matched — enough to flag it. The run is\n // terminated by a non-base62 lookahead (not \\b, which a trailing `_` — a word\n // char — would not fire), so an underscore-adjacent key still matches.\n // Assumption + chosen tradeoff: a real key opens with a >=20-char base62 run,\n // so the {20,} floor is what separates a key from a kebab identifier. A key\n // whose FIRST segment is shorter than 20 (e.g. `sk-proj-abc123_` then more,\n // broken up by underscores) slips past this BARE-PASTE detector; that is\n // accepted, because such a value in an assignment still warns via\n // secret-assignment — the bare-paste path is the only gap.\n re: /\\bsk-(?!ant-)(?:proj-|svcacct-|admin-)?(?=[0-9A-Za-z]*[0-9])[0-9A-Za-z]{20,}(?![0-9A-Za-z])/g,\n excerpt: (m) => maskKeeping(m[0], 3),\n },\n {\n check: 'google-key',\n severity: 'block',\n // gitleaks gcp-api-key (AIza) and gcp-oauth-client-secret (GOCSPX-).\n re: /\\b(?:AIza[0-9A-Za-z_-]{35}|GOCSPX-[0-9A-Za-z_-]{20,})\\b/g,\n excerpt: (m) => maskKeeping(m[0], m[0].startsWith('AIza') ? 4 : 7),\n },\n {\n check: 'npm-token',\n severity: 'block',\n // gitleaks npm-access-token.\n re: /\\bnpm_[0-9A-Za-z]{36}\\b/g,\n excerpt: (m) => maskKeeping(m[0], 4),\n },\n {\n check: 'db-connection-uri',\n severity: 'block',\n // A connection string with an embedded password (scheme://user:pass@host).\n // Only the password (group 3) is secret; the excerpt masks it and keeps the\n // rest so the finding is legible. Placeholder-gated like the other high-\n // confidence shapes so a docs example (postgres://postgres:postgres@…,\n // ://user:<password>@…) doesn't hard-block; a real password still blocks.\n re: /\\b([a-z][a-z0-9+.-]*):\\/\\/([^\\s:@/]+):([^\\s@/]+)@([^\\s/:]+)/gi,\n excerpt: (m) => `${m[1]}://${m[2]}:[redacted]@${m[4]}`,\n skip: (m) => isPlaceholder(m[3] ?? '') || isExamplePassword(m[3] ?? ''),\n },\n {\n check: 'bearer-token',\n severity: 'block',\n // An Authorization: Bearer header carrying a live token; placeholder-gated\n // like secret-assignment so `Bearer <token>` examples don't hard-block.\n re: /\\bAuthorization:\\s*Bearer\\s+(\\S{8,})/gi,\n excerpt: (m) => `Authorization: Bearer [redacted ${m[1]?.length ?? 0} chars]`,\n skip: (m) => isPlaceholder(m[1] ?? ''),\n },\n // Generic secret-named assignment — WARN, not block (review): a keyword match is\n // lower-confidence than a structured shape, and a warn still forces confirmation\n // under `review` and `auto`, while benign config (SECRET_NAME=…,\n // MYSQL_ROOT_PASSWORD=…) is not permanently non-bypassable. `full-auto` and a bare\n // `--yes` DO clear it unseen, which is the price of that choice; the publish skill\n // says so rather than implying keys and tokens are all in the blocking tier. The\n // excerpt stays masked. Placeholder and structural (path/URL/regex) values are\n // skipped entirely.\n {\n check: 'secret-assignment',\n severity: 'warn',\n // Key: api[_-]?key, secret, access/private key, passw(or)?d, token,\n // credential(s), auth token — camelCase-insensitive. Value: a quoted string\n // (interior spaces allowed) or an unquoted run, ≥6 chars. Value is masked.\n re: /\\b([A-Za-z0-9_]*(?:API[_-]?KEY|SECRET|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|PASSW(?:OR)?D|TOKEN|CREDENTIALS?|AUTH[_-]?TOKEN)[A-Za-z0-9_]*)\\s*[:=]\\s*(\"[^\"]{6,}\"|'[^']{6,}'|[^\\s\"']{6,})/gi,\n excerpt: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? '').length} chars]`,\n skip: skipNonLiteralValue,\n },\n // Wallet addresses — warn (a contract address may be intentional). Not a secret,\n // shown abbreviated. viem's checksum validation is deliberately NOT used to gate\n // this: EIP-55 strict validation rejects the valid all-lowercase/all-uppercase\n // forms, which a scanner must still surface, so shape matching is the right test.\n {\n check: 'wallet-address',\n severity: 'warn',\n re: /(?<![0-9a-fx])0x[0-9a-fA-F]{40}(?![0-9a-fA-F])/gi,\n excerpt: (m) => `${m[0].slice(0, 6)}…${m[0].slice(-4)}`,\n },\n // Employer-internal markers — warn. Marker-SHAPED, not word-in-phrase (#36):\n // the detector targets the classification legend a document stamp carries\n // (CONFIDENTIAL, CONFIDENTIAL DRAFT/INFORMATION, STRICTLY/COMPANY\n // CONFIDENTIAL, \"Acme Inc. Confidential\", INTERNAL (USE) ONLY, DO NOT\n // DISTRIBUTE), so it is case-SENSITIVE — prose about \"confidential computing\"\n // never fires. The phrase-vs-legend split is positional, not a blanket\n // next-word lookahead (review r5: the old lookahead lost CONFIDENTIAL\n // INFORMATION and every title-case legend):\n // - all-caps CONFIDENTIAL is suppressed only when all-caps words flank it on\n // BOTH sides — that is what a mid-phrase mention in a shouting heading\n // looks like (A SURVEY OF CONFIDENTIAL COMPUTING …). A legend either leads\n // its line (CONFIDENTIAL DRAFT) or ends it (ACME CONFIDENTIAL, HIGHLY\n // CONFIDENTIAL, PROPRIETARY AND CONFIDENTIAL), so one-sided caps still\n // fire (review r6: the caps-prefixed company stamp is the most common real\n // legend form, and the old left-only rule missed the whole family).\n // Accepted FP: a caps heading that LEADS with the topic word\n // (# CONFIDENTIAL COMPUTING ON AWS) warns — fail-safe direction. Accepted\n // FN: a caps-flanked legend without a whitelisted prefix (ACME\n // CONFIDENTIAL INFORMATION) is indistinguishable from a shouting-heading\n // phrase and misses; STRICTLY/COMPANY/HIGHLY prefixes are legend-only\n // vocabulary and are whitelisted through.\n // - Title-case Confidential fires only before punctuation or end-of-line\n // (\"Acme Inc. Confidential\", \"## Confidential: …\"), never mid-title\n // (\"Confidential Computing: a TEE survey\").\n {\n check: 'confidential-marker',\n severity: 'warn',\n re: /\\b(?:STRICTLY|COMPANY|HIGHLY)\\s+CONFIDENTIAL\\b|(?<![A-Z]{2,}[ \\t]+)\\bCONFIDENTIAL\\b|\\bCONFIDENTIAL\\b(?![ \\t]+[A-Z]{2,})|\\bConfidential(?=\\s*(?:[-:.,;–—]|$))|\\b(?:INTERNAL|Internal)(?:\\s+(?:USE|Use))?\\s+(?:ONLY|Only)\\b|\\b(?:DO\\s+NOT\\s+DISTRIBUTE|Do\\s+Not\\s+Distribute)\\b/g,\n excerpt: (m) => m[0],\n },\n {\n check: 'internal-hostname',\n severity: 'warn',\n re: /\\b(?:[a-z0-9-]+\\.)+(?:internal|corp|local|lan|intranet)\\b/gi,\n excerpt: (m) => m[0],\n },\n // Home-anchored local filesystem paths — warn (open-questions publishing-safety:\n // private paths). A /Users/<name>/… or /home/<name>/… or C:\\Users\\<name>\\…\n // path leaks the machine username and private project layout. The username\n // segment is masked in the excerpt; obvious placeholder usernames\n // (/home/user/…, /Users/username/…) are docs examples and skip. `~/…` paths\n // deliberately do NOT fire: they are already generalized. The unix branch\n // requires a non-name left boundary so a web-URL path segment\n // (docs.example.com/home/…) is not a local path, and the segment class\n // excludes `?`/`&` so a query string (…?api_key=…) is never swallowed into a\n // verbatim excerpt a sibling detector would have masked (review r5). Windows\n // matches [Uu]sers: the filesystem is case-insensitive.\n {\n check: 'local-path',\n severity: 'warn',\n re: /(?:(?<![\\w.-])\\/(?:Users|home)\\/([A-Za-z0-9._-]+)(?:\\/[^\\s\"'`)\\]}>:,;?&]+)+|\\b[A-Za-z]:\\\\[Uu]sers\\\\([^\\\\\\s\"']+)(?:\\\\[^\\\\\\s\"']+)+)/dg,\n excerpt: (m) => {\n // Splice at the capture's own offsets (d-flag indices): a plain\n // String.replace masked the FIRST occurrence of the username, which for a\n // username that is a substring of the /Users|/home prefix mangled the\n // prefix and echoed the real username (review r5).\n const bounds = m.indices?.[1] ?? m.indices?.[2];\n const masked =\n bounds === undefined\n ? m[0]\n : `${m[0].slice(0, bounds[0] - m.index)}[user]${m[0].slice(bounds[1] - m.index)}`;\n return masked.length > 60 ? `${masked.slice(0, 57)}…` : masked;\n },\n skip: (m) => PLACEHOLDER_USERNAME.test(m[1] ?? m[2] ?? ''),\n },\n // Labeled customer/account identifiers — warn (open-questions publishing-safety:\n // customer identifiers). Fires only on the explicit label + separator + value\n // shape (customer_id: 84213, Account Number: ACME-0042); the value is masked\n // like a secret-assignment value since a customer identifier is third-party\n // data. Chosen tradeoff: an unlabeled identifier (bare CUST-4812) is a false\n // negative — an unlabeled token is indistinguishable from a SKU or version tag.\n {\n check: 'customer-identifier',\n severity: 'warn',\n re: /\\b((?:customer|client|account|tenant|subscriber)[ _-]?(?:id|number|no))\\b\\s*[:=#]\\s*(\"[^\"]{2,}\"|'[^']{2,}'|[A-Za-z0-9][A-Za-z0-9._-]{2,})/gi,\n excerpt: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? '').length} chars]`,\n skip: skipNonLiteralValue,\n },\n // Third-party paid/licensed-content markers — warn (open-questions\n // publishing-safety: third-party copyrighted inputs). A rights LEGEND in the\n // draft suggests copied licensed material; ambiguity-class (the author may\n // hold the rights), so warn, never block. Legend shapes only — bare paywall\n // vocabulary (paywalled, premium content, subscriber-only, behind a paywall)\n // deliberately does NOT fire: it is this marketplace's own subject matter and\n // measured 100% false-positive on the dogfood corpus (review r5), the exact\n // word-in-phrase failure #36 is about.\n {\n check: 'paid-content-marker',\n severity: 'warn',\n re: /\\ball rights reserved\\b|\\b(?:reprinted|reproduced|used) with permission\\b|\\bnot for (?:redistribution|republication)\\b|\\bdo not (?:redistribute|republish)\\b|(?:©|\\(c\\)|copyright)\\s*(?:19|20)\\d{2}\\b/gi,\n excerpt: (m) => m[0],\n },\n // Embedded prompt/tool-output instruction patterns — warn (open-questions\n // publishing-safety: embedded instructions). Source material captured from\n // prompts or tool output can carry injection-shaped imperatives that would\n // ship to every future buyer. High-precision imperative shapes only: a bare\n // \"system prompt\" mention, chat-template delimiters (<system>, [INST]), and\n // persona phrases (\"you are an assistant\", \"as an AI\") deliberately do NOT\n // fire — legitimate agent-engineering exposition quotes all of them\n // constantly (review r5), and only the imperative shapes are injection-typed.\n // Two entries under one check name: the imperative shapes are case-INsensitive\n // (adversarial text uses any case), while BEGIN SYSTEM/HIDDEN PROMPT is\n // case-SENSITIVE — its signal is that it reads as a document header, and\n // lowercase \"begin system prompt\" is ordinary prose on this marketplace's own\n // subject matter (greptile r7), the #36 word-in-phrase class again.\n {\n check: 'embedded-instruction',\n severity: 'warn',\n re: /\\b(?:ignore|disregard|forget)\\s+(?:all\\s+|any\\s+)?(?:previous|prior|above|earlier|preceding)\\s+(?:instructions?|prompts?|context|messages?)\\b|\\bdo not (?:reveal|disclose|mention) (?:this|these|the above)\\b/gi,\n excerpt: (m) => m[0],\n },\n {\n check: 'embedded-instruction',\n severity: 'warn',\n re: /\\bBEGIN (?:SYSTEM|HIDDEN) (?:PROMPT|INSTRUCTIONS)\\b/g,\n excerpt: (m) => m[0],\n },\n // Personal data — warn. `email` subsumes corp-domain emails (an internal marker).\n {\n check: 'email',\n severity: 'warn',\n re: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n excerpt: (m) => m[0],\n },\n {\n check: 'phone',\n severity: 'warn',\n re: /(?<!\\d)(?:\\+?\\d{1,2}[\\s.-]?)?(?:\\(\\d{3}\\)|\\d{3})[\\s.-]\\d{3}[\\s.-]\\d{4}(?!\\d)/g,\n excerpt: (m) => m[0],\n },\n];\n\nfunction scanLineDetectors(lines: string[]): ScanFinding[] {\n const out: ScanFinding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n for (const detector of LINE_DETECTORS) {\n detector.re.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = detector.re.exec(line)) !== null) {\n if (!detector.skip?.(m)) {\n out.push({\n check: detector.check,\n severity: detector.severity,\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: detector.excerpt(m),\n });\n }\n // Every detector pattern matches at least one character, so a global\n // exec() always advances lastIndex — no zero-width-match loop guard needed.\n }\n }\n }\n return out;\n}\n\n// Accepted alpha gaps (owner call, tracked for post-alpha): BIP-39 mnemonic\n// phrases (12/24 dictionary words) are NOT detected — a wordlist match is\n// high-false-positive against prose and deferred. An all-lowercase, digit-free\n// literal (a diceware/xkcd passphrase, e.g. PASSWORD=correcthorsebatterystaple)\n// parses as a bare identifier and yields NO finding for the same reason — a\n// dictionary-word run is indistinguishable from prose; chosen, warn-tier, and\n// filed next to BIP-39. Headerless base64/DER-encoded private keys (no\n// -----BEGIN----- marker) are likewise NOT detected; only the PEM-armored form\n// and the 0x-64-hex form are.\n\n/**\n * Shared skip for labeled-value detectors (secret-assignment,\n * customer-identifier — one helper so the two cannot drift): drop a value that\n * is a placeholder, a structural path/URL/regex, or — when UNQUOTED only, a\n * quoted string is a literal — a code expression (config.clientSecret,\n * user.account_id, hashAndSalt(input), a bare lowercase identifier).\n */\nfunction skipNonLiteralValue(m: RegExpExecArray): boolean {\n const raw = m[2] ?? '';\n const value = dequote(raw);\n if (isPlaceholder(value) || isStructural(value)) return true;\n return raw === value && isCodeExpression(value);\n}\n\n/** Strip a single matching pair of surrounding quotes from a captured value. */\nfunction dequote(value: string): string {\n const m = /^\"([^\"]*)\"$|^'([^']*)'$/.exec(value);\n return m !== null ? (m[1] ?? m[2] ?? '') : value;\n}\n\n// Placeholder tokens must match the WHOLE value, never merely a prefix: an early\n// prefix-anchored version let real secrets through (mySecretP@ss123,\n// yourCompanyProdKey_abc123, exampleRealKey99) and, because isPlaceholder also\n// gates the block-tier bearer/db-uri detectors, that was a block bypass.\nconst PLACEHOLDER_WORD =\n /^(?:xxx+|example|example-value|placeholder|redacted|changeme|dummy|sample|todo|tbd|none|null|secret|test|\\*+|\\.{3,})$/i;\n// your-/my- style kebab or snake placeholders (your-api-key, my_secret,\n// your-key-here) — lowercase words only, so a camelCase/digit-bearing real value\n// (yourCompanyProdKey_abc123) is NOT treated as a placeholder.\nconst PLACEHOLDER_PREFIX = /^(?:your|my)[-_][a-z]+(?:[-_][a-z]+)*$/i;\n\n/** A secret-assignment value that is an obvious placeholder, not a live secret. */\nfunction isPlaceholder(value: string): boolean {\n if (/^[<${%]/.test(value)) return true; // <your-key>, ${VAR}, {{x}}, %ENV%\n return PLACEHOLDER_WORD.test(value) || PLACEHOLDER_PREFIX.test(value);\n}\n\n/**\n * A right-hand side that is code, not a literal secret: a member/property access\n * (user.password), a call (hashAndSalt(input)), or a bare lowercase/snake-case\n * identifier reference (password, db_password). Only applied to UNQUOTED values —\n * a quoted string is a literal. camelCase / digit-bearing tokens are NOT code\n * (they read as opaque secrets), so a real value still fires.\n */\nfunction isCodeExpression(value: string): boolean {\n // Trailing code punctuation the value capture drags in (process.env.KEY, ).\n const v = value.replace(/[,;]+$/, '');\n if (/^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/.test(v)) return true; // a.b.c\n if (/^[A-Za-z_$][\\w$.]*\\([^)]*\\)$/.test(v)) return true; // f(...)\n // A call truncated at a quoted arg by the value capture: os.environ.get(\n if (/\\($/.test(v)) return true;\n return /^[a-z_$][a-z_$]*$/.test(v); // bare lowercase identifier\n}\n\n/** A structural value (path, URL, or regex literal), not a literal secret. */\nfunction isStructural(value: string): boolean {\n return /^(?:\\.?\\.?\\/|~\\/|https?:\\/\\/|\\^)/.test(value);\n}\n\n// Well-known example/default DB passwords — a connection string using one is a\n// docs snippet, not a leaked credential.\nconst EXAMPLE_PASSWORDS = new Set([\n 'password',\n 'postgres',\n 'mysql',\n 'root',\n 'admin',\n 'changeme',\n 'example',\n 'secret',\n 'test',\n 'guest',\n 'toor',\n]);\n\n/** A db-connection-uri password that is an obvious example/default, not a secret. */\nfunction isExamplePassword(password: string): boolean {\n return EXAMPLE_PASSWORDS.has(password.toLowerCase());\n}\n\n// EVM raw private key (0x + 64 hex) vs. a 32-byte hash. On Base the two are\n// syntactically identical, and a block finding is permanently non-bypassable, so\n// a post carrying an x402 receipt / basescan tx hash must not be hard-blocked.\n// A 64-hex is demoted to a warn 'hex32-value' when the context reads as a hash:\n// it sits inside an http(s) URL token, or is labelled tx/txhash/txn/hash/\n// blockhash just before it. A bare, uncontextualized 64-hex stays a block\n// 'raw-private-key' (continuing the BlockRun-credited wallet-key scanner).\nconst HEX64_RE = /(?<![0-9a-fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/gi;\nconst HASH_LABEL_RE = /(?:^|[^a-z0-9])(?:blockhash|txhash|txn|tx|hash)[\\s/:=]*$/i;\n\nfunction scanHex64(lines: string[]): ScanFinding[] {\n const out: ScanFinding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n HEX64_RE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = HEX64_RE.exec(line)) !== null) {\n const hash = isHashContext(line, m.index);\n out.push({\n check: hash ? 'hex32-value' : 'raw-private-key',\n severity: hash ? 'warn' : 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: hash ? `${m[0].slice(0, 6)}…${m[0].slice(-4)}` : maskKeeping(m[0], 2),\n });\n }\n }\n return out;\n}\n\nfunction isHashContext(line: string, matchIndex: number): boolean {\n const before = line.slice(0, matchIndex);\n if (HASH_LABEL_RE.test(before)) return true;\n // The whitespace-delimited token containing the match starts with http(s)://.\n const prefix = /(\\S*)$/.exec(before)?.[1] ?? '';\n return /^https?:\\/\\//.test(line.slice(matchIndex - prefix.length));\n}\n\n// gitleaks private-key marker (RSA/EC/OPENSSH/PGP variants, optional BLOCK).\nconst PEM_BEGIN = /-----BEGIN[ A-Z0-9]*PRIVATE KEY(?: BLOCK)?-----/;\n\n/** A PEM private-key block is a single block finding on its BEGIN marker line. */\nfunction scanPemBlocks(lines: string[]): ScanFinding[] {\n const out: ScanFinding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const m = PEM_BEGIN.exec(line);\n if (m !== null) {\n out.push({\n check: 'pem-private-key',\n severity: 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: m[0], // the header marker only — no key material follows on it\n });\n }\n }\n return out;\n}\n\nconst FENCE = /^(\\s*)(`{3,}|~{3,})/;\n\n/**\n * Long verbatim runs — warn (a rights, not a secrets, concern). A fenced code\n * block or a contiguous `>` blockquote whose content reaches LONG_QUOTE_WORDS\n * reads as copied third-party material. Reported once on the run's first line.\n */\nfunction scanLongVerbatim(lines: string[]): ScanFinding[] {\n const out: ScanFinding[] = [];\n let i = 0;\n while (i < lines.length) {\n const line = lines[i] ?? '';\n const fence = FENCE.exec(line);\n if (fence !== null) {\n const marker = fence[2] ?? '```';\n const start = i;\n const body: string[] = [];\n i++;\n while (i < lines.length && !closesFence(lines[i] ?? '', marker)) {\n body.push(lines[i] ?? '');\n i++;\n }\n i++; // consume the closing fence (or run off the end)\n pushIfLong(out, body, start, line);\n continue;\n }\n if (/^\\s*>/.test(line)) {\n const start = i;\n const body: string[] = [];\n while (i < lines.length && /^\\s*>/.test(lines[i] ?? '')) {\n body.push((lines[i] ?? '').replace(/^\\s*>\\s?/, ''));\n i++;\n }\n pushIfLong(out, body, start, lines[start] ?? '');\n continue;\n }\n i++;\n }\n return out;\n}\n\nfunction closesFence(line: string, marker: string): boolean {\n const m = FENCE.exec(line);\n return m !== null && (m[2] ?? '').startsWith(marker);\n}\n\nfunction pushIfLong(\n out: ScanFinding[],\n body: string[],\n startLine: number,\n firstLine: string,\n): void {\n const text = body.join(' ').trim();\n const words = text.length === 0 ? 0 : text.split(/\\s+/).length;\n if (words < LONG_QUOTE_WORDS) return;\n const excerpt = text.length > 60 ? `${text.slice(0, 57)}…` : text;\n out.push({\n check: 'long-verbatim-quote',\n severity: 'warn',\n line: startLine + 1,\n span: [0, firstLine.length],\n excerpt,\n });\n}\n\n/**\n * Deterministic order: line, then start column, then check name. Exact duplicate\n * spans of the same check (e.g. two detectors on the same offset) collapse to one.\n */\nfunction dedupeAndSort(findings: ScanFinding[]): ScanFinding[] {\n const seen = new Set<string>();\n const unique = findings.filter((f) => {\n const key = `${f.check}:${f.line}:${f.span[0]}:${f.span[1]}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.sort(\n (a, b) => a.line - b.line || a.span[0] - b.span[0] || a.check.localeCompare(b.check),\n );\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\n\n/**\n * Derive the deterministic publish-time scan context from the source project:\n * the git remote `org/repo` slugs of the repository containing `cwd` (the\n * open-questions publishing-safety \"private repository/org names\" check). A\n * draft written while working in a project routinely quotes that project's own\n * remote or slug; the scan treats those as private-by-default and warns.\n *\n * Offline and best-effort by design: a plain filesystem read of `.git/config`\n * (including the worktree `.git`-file indirection), no `git` subprocess, no\n * network. Anything unreadable or unparseable yields `[]` — the scan must never\n * fail a publish because the source dir is not a git checkout.\n */\nexport async function deriveProjectMarkers(cwd: string): Promise<string[]> {\n try {\n const configPath = await findGitConfig(resolve(cwd));\n if (configPath === undefined) return [];\n const config = await readSmallFile(configPath);\n return config === undefined ? [] : extractRemoteSlugs(config);\n } catch {\n return [];\n }\n}\n\n/**\n * Real .git plumbing files are tiny; anything bigger is not one. The cap plus\n * the isFile() gate keep the \"never fail a publish\" contract honest against a\n * crafted or broken checkout: an unbounded readFile of a FIFO hangs forever and\n * of a device/huge file dies on an uncatchable OOM (review r5).\n */\nconst MAX_GIT_FILE_BYTES = 1024 * 1024;\n\n/** Read a regular file of sane size, or undefined — never hang, never throw. */\nasync function readSmallFile(path: string): Promise<string | undefined> {\n const s = await stat(path).catch(() => undefined);\n if (s?.isFile() !== true || s.size > MAX_GIT_FILE_BYTES) return undefined;\n return readFile(path, 'utf8').catch(() => undefined);\n}\n\n/** Walk up from `dir` to the filesystem root looking for a `.git` dir or file. */\nasync function findGitConfig(dir: string): Promise<string | undefined> {\n for (let current = dir; ; current = dirname(current)) {\n const dotGit = join(current, '.git');\n const s = await stat(dotGit).catch(() => undefined);\n if (s?.isDirectory() === true) return join(dotGit, 'config');\n if (s?.isFile() === true) {\n const resolved = await resolveGitFile(dotGit, current);\n if (resolved !== undefined) return resolved;\n }\n if (dirname(current) === current) return undefined;\n }\n}\n\n/**\n * A `.git` FILE is a worktree/submodule indirection: `gitdir: <path>`. The\n * shared config lives in the common dir (a `commondir` file inside the gitdir\n * points at it); a submodule's gitdir carries its own `config` directly.\n */\nasync function resolveGitFile(\n dotGitFile: string,\n containingDir: string,\n): Promise<string | undefined> {\n const content = await readSmallFile(dotGitFile);\n if (content === undefined) return undefined;\n const m = /^gitdir:\\s*(.+)\\s*$/m.exec(content);\n if (m?.[1] === undefined) return undefined;\n const gitdir = isAbsolute(m[1]) ? m[1] : resolve(containingDir, m[1]);\n const commondirFile = await readSmallFile(join(gitdir, 'commondir'));\n if (commondirFile !== undefined) {\n const common = commondirFile.trim();\n return join(isAbsolute(common) ? common : resolve(gitdir, common), 'config');\n }\n return join(gitdir, 'config');\n}\n\n// Section headers and `url = <value>` lines; git config keys are case-insensitive.\nconst SECTION_LINE = /^\\s*\\[([^\\]]*)\\]/;\nconst URL_LINE = /^\\s*url\\s*=\\s*(.+?)\\s*$/i;\n\n/**\n * Reduce each remote URL to its repository path slug (`org/repo`, or the full\n * `group/sub/repo` path on deep hosts), handling both scp-like\n * (`git@host:org/repo.git`) and URL (`https://host/org/repo.git`,\n * `ssh://git@host/org/repo`) forms. The slug — not the bare repo name — is the\n * marker: a bare name is too collision-prone against ordinary prose.\n */\nexport function extractRemoteSlugs(gitConfig: string): string[] {\n // Section-aware, like git itself: only `[remote …]` sections carry remote\n // URLs — an [lfs]/[url \"…\"] `url =` key is NOT a remote and produced dead\n // markers (review r5). Inline `#`/`;` comments are stripped (a remote URL\n // never carries either).\n const slugs = new Set<string>();\n let inRemoteSection = false;\n for (const line of gitConfig.split('\\n')) {\n const section = SECTION_LINE.exec(line);\n if (section !== null) {\n inRemoteSection = /^remote\\b/i.test((section[1] ?? '').trim());\n continue;\n }\n if (!inRemoteSection) continue;\n const m = URL_LINE.exec(line);\n if (m === null) continue;\n const value = (m[1] ?? '').split(/[#;]/, 1)[0]?.trim() ?? '';\n const slug = slugFromRemoteUrl(value);\n if (slug !== undefined) slugs.add(slug);\n }\n return [...slugs];\n}\n\nfunction slugFromRemoteUrl(url: string): string | undefined {\n let path: string | undefined;\n const scheme = /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^/@\\s]+@)?[^/\\s]+\\/(.+)$/i.exec(url);\n const scp = /^[^/@\\s]+@[^:/\\s]+:(.+)$/.exec(url);\n if (scheme !== null) path = scheme[1];\n else if (scp !== null) path = scp[1];\n if (path === undefined) return undefined;\n const slug = path\n .replace(/^\\/+/, '')\n .replace(/\\/+$/, '')\n .replace(/\\.git$/i, '');\n // A slug needs at least org/name to be a meaningful private-reference marker.\n return slug.includes('/') && slug.length >= 3 ? slug : undefined;\n}\n","import { CliError } from './errors';\nimport { ATOMIC_RE, UUID_RE } from './ids';\n\n/**\n * The answer-card (`resource`) authoring layer (A3, spec 09 §4). Derives the\n * machine-readable card from YAML frontmatter (a minimal in-repo parser — no YAML\n * dependency is added to a wallet-holding CLI with an otherwise empty dep tree)\n * and the card-authoring flags, flags winning, and validates it LOCALLY against\n * the exact server bounds so a malformed card fails as USAGE (exit 2) before any\n * network round trip. Field rejections use the server's dotted `resource.<field>`\n * key convention (flattenPostError) so a local error reads identically to a\n * server-returned one.\n */\n\nexport type FrontmatterValue = string | string[] | Record<string, string[]>;\nexport type Frontmatter = Record<string, FrontmatterValue>;\n\nexport interface ParsedDocument {\n frontmatter: Frontmatter;\n body: string;\n}\n\n/** The card fields the CLI sends; mirrors resourceMetadataInputSchema (A3). */\nexport interface ResourceCardInput {\n artifactType?: 'document' | 'skill' | 'dataset';\n mediaType?: string;\n temporalMode?: 'snapshot' | 'maintained' | 'evergreen';\n asOf?: string;\n validUntil?: string;\n supersedesPostId?: string;\n questionsAnswered?: string[];\n tasksSupported?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: Record<string, string[]>;\n provenanceSummary?: string;\n methodologySummary?: string;\n maintenanceCadence?: string;\n reproductionMinutes?: number;\n estimatedPaidInputCost?: string;\n}\n\n/** The card-authoring flags (each maps 1:1 to a card field; flags beat frontmatter). */\nexport interface CardFlags {\n question?: string[];\n task?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: Record<string, string[]>;\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Minimal frontmatter parser.\n// ---------------------------------------------------------------------------\n\nconst FRONTMATTER_RE = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/;\n\n/**\n * Split a leading `--- ... ---` YAML frontmatter block from the body. Supports\n * exactly the shapes a card needs — `key: value` scalars, block sequences (`key:`\n * then ` - item`), inline flow sequences (`key: [a, b]`), and a one-level nested\n * map (for `appliesTo`) whose sub-values are sequences — and refuses anything\n * else as USAGE, so an unsupported construct fails loudly, never silently\n * mis-parsed. No frontmatter ⇒ empty map + the whole text as body.\n */\nexport function parseFrontmatter(text: string): ParsedDocument {\n const match = FRONTMATTER_RE.exec(text);\n if (match === null) return { frontmatter: {}, body: text };\n const block = match[1] ?? '';\n const body = text.slice(match[0].length);\n return { frontmatter: parseBlock(block), body };\n}\n\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length;\n}\n\nfunction parseBlock(block: string): Frontmatter {\n const lines = block.split(/\\r?\\n/).filter((l) => l.trim().length > 0 && !/^\\s*#/.test(l));\n const out: Frontmatter = {};\n let i = 0;\n while (i < lines.length) {\n const line = lines[i] ?? '';\n if (indentOf(line) !== 0) {\n throw usage(`Unexpected indentation in frontmatter: ${JSON.stringify(line)}`);\n }\n const kv = splitKey(line);\n if (kv === null) throw usage(`Malformed frontmatter line: ${JSON.stringify(line)}`);\n const { key, value } = kv;\n if (value.length > 0) {\n out[key] = parseInlineValue(value);\n i++;\n continue;\n }\n // A `key:` with no inline value: an indented block sequence or nested map.\n const child: string[] = [];\n i++;\n while (i < lines.length && indentOf(lines[i] ?? '') > 0) {\n child.push(lines[i] ?? '');\n i++;\n }\n if (child.length === 0) {\n out[key] = '';\n } else if (child.every((c) => /^\\s*-\\s/.test(c))) {\n out[key] = child.map((c) => unquote(c.replace(/^\\s*-\\s+/, '').trim()));\n } else {\n out[key] = parseNestedMap(child);\n }\n }\n return out;\n}\n\n/** A one-level nested map (appliesTo): each `subkey: [..]` or `subkey:` + `- item`. */\nfunction parseNestedMap(lines: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n const baseIndent = indentOf(lines[0] ?? '');\n let i = 0;\n while (i < lines.length) {\n const line = lines[i] ?? '';\n if (indentOf(line) !== baseIndent)\n throw usage(`Malformed nested frontmatter: ${JSON.stringify(line)}`);\n const kv = splitKey(line);\n if (kv === null) throw usage(`Malformed nested frontmatter line: ${JSON.stringify(line)}`);\n const { key, value } = kv;\n if (value.length > 0) {\n const parsed = parseInlineValue(value);\n out[key] = Array.isArray(parsed) ? parsed : [parsed as string];\n i++;\n continue;\n }\n const items: string[] = [];\n i++;\n while (i < lines.length && indentOf(lines[i] ?? '') > baseIndent) {\n const c = lines[i] ?? '';\n if (!/^\\s*-\\s/.test(c))\n throw usage(`Expected a list item in frontmatter: ${JSON.stringify(c)}`);\n items.push(unquote(c.replace(/^\\s*-\\s+/, '').trim()));\n i++;\n }\n out[key] = items;\n }\n return out;\n}\n\nfunction splitKey(line: string): { key: string; value: string } | null {\n const m = /^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*:\\s?(.*)$/.exec(line);\n if (m === null || m[1] === undefined) return null;\n guardKey(m[1]);\n return { key: m[1], value: (m[2] ?? '').trim() };\n}\n\n/**\n * Reject a prototype-polluting key BEFORE it is used to index a plain object:\n * a `__proto__`/`constructor`/`prototype` key would otherwise mutate the local\n * object's prototype (silently dropping the field) or throw a raw TypeError, both\n * of which contradict the fail-loudly contract. Fails as USAGE instead.\n */\nconst UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\nfunction guardKey(key: string): void {\n if (UNSAFE_KEYS.has(key)) {\n throw new CliError('USAGE', `Unsupported key: ${JSON.stringify(key)}`, {\n fix: 'Rename it; __proto__, constructor, and prototype are not allowed as keys.',\n });\n }\n}\n\nfunction parseInlineValue(value: string): string | string[] {\n if (value.startsWith('[') && value.endsWith(']')) {\n const inner = value.slice(1, -1).trim();\n if (inner.length === 0) return [];\n return inner.split(',').map((v) => unquote(v.trim()));\n }\n return unquote(value);\n}\n\nfunction unquote(value: string): string {\n if (\n (value.startsWith('\"') && value.endsWith('\"') && value.length >= 2) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\") && value.length >= 2)\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Card derivation + local validation.\n// ---------------------------------------------------------------------------\n\nconst ARTIFACT_TYPES = ['document', 'skill', 'dataset'] as const;\nconst TEMPORAL_MODES = ['snapshot', 'maintained', 'evergreen'] as const;\n// Case-insensitive per RFC 2045 (the server's regex carries /i; the OpenAPI\n// pattern can't express the flag, so `text/Markdown` is contract-legal).\nconst MEDIA_TYPE_RE = /^[a-z0-9]+\\/[a-z0-9][a-z0-9.+-]*$/i;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n// Seconds (and fractional seconds) are OPTIONAL, matching the server's date-time\n// pattern; the offset (Z or ±hh:mm) is required.\nconst ISO_OFFSET_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:\\d{2})$/;\n\n/** Collects field errors under dotted `resource.<field>` keys, then throws once. */\nclass CardErrors {\n private readonly fieldErrors: Record<string, string[]> = {};\n add(field: string, message: string): void {\n const key = `resource.${field}`;\n (this.fieldErrors[key] ??= []).push(message);\n }\n get empty(): boolean {\n return Object.keys(this.fieldErrors).length === 0;\n }\n throwIfAny(): void {\n if (this.empty) return;\n const first = Object.entries(this.fieldErrors)[0];\n const summary = first !== undefined ? `${first[0]}: ${first[1][0]}` : 'invalid card';\n throw new CliError('USAGE', `Invalid answer card (${summary})`, {\n fix: 'Correct the reported resource.<field> values (frontmatter or flags), then re-run.',\n details: { fieldErrors: this.fieldErrors },\n });\n }\n}\n\n/**\n * Derive + validate the `resource` card from frontmatter (card keys) and flags,\n * flags winning per field. Returns undefined when NO card field is present (an\n * empty `resource` is a server no-op, so the CLI omits it rather than sending\n * `{}`). Throws USAGE with dotted `resource.<field>` errors on any bound miss.\n */\nexport function deriveCard(\n frontmatter: Frontmatter,\n flags: CardFlags,\n): ResourceCardInput | undefined {\n const errs = new CardErrors();\n const card: ResourceCardInput = {};\n\n const scalar = (fmKey: string, flagVal: string | undefined): string | undefined => {\n if (flagVal !== undefined) return flagVal;\n const fm = frontmatter[fmKey];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n errs.add(fmKey, 'expected a single string value');\n return undefined;\n }\n return fm;\n };\n\n const list = (fmKey: string, flagVal: string[] | undefined): string[] | undefined => {\n if (flagVal !== undefined && flagVal.length > 0) return flagVal;\n const fm = frontmatter[fmKey];\n if (fm === undefined) return undefined;\n if (!Array.isArray(fm)) {\n errs.add(fmKey, 'expected a list');\n return undefined;\n }\n return fm;\n };\n\n const artifactType = scalar('artifactType', flags.artifactType);\n if (artifactType !== undefined) {\n if ((ARTIFACT_TYPES as readonly string[]).includes(artifactType)) {\n card.artifactType = artifactType as ResourceCardInput['artifactType'];\n } else {\n errs.add('artifactType', `must be one of ${ARTIFACT_TYPES.join(', ')}`);\n }\n }\n\n const mediaType = scalar('mediaType', undefined);\n if (mediaType !== undefined) {\n if (mediaType.length > 100) errs.add('mediaType', 'must be at most 100 characters');\n else if (!MEDIA_TYPE_RE.test(mediaType))\n errs.add('mediaType', 'must be a MIME type, e.g. text/markdown');\n else card.mediaType = mediaType;\n }\n\n const temporalMode = scalar('temporalMode', flags.temporalMode);\n if (temporalMode !== undefined) {\n if ((TEMPORAL_MODES as readonly string[]).includes(temporalMode)) {\n card.temporalMode = temporalMode as ResourceCardInput['temporalMode'];\n } else {\n errs.add('temporalMode', `must be one of ${TEMPORAL_MODES.join(', ')}`);\n }\n }\n\n const asOf = validateIso(scalar('asOf', flags.asOf), 'asOf', errs);\n if (asOf !== undefined) card.asOf = asOf;\n const validUntil = validateIso(scalar('validUntil', flags.validUntil), 'validUntil', errs);\n if (validUntil !== undefined) card.validUntil = validUntil;\n if (asOf !== undefined && validUntil !== undefined && Date.parse(validUntil) < Date.parse(asOf)) {\n errs.add('validUntil', 'must be at or after asOf');\n }\n\n const supersedes = scalar('supersedesPostId', undefined);\n if (supersedes !== undefined) {\n if (UUID_RE.test(supersedes)) card.supersedesPostId = supersedes;\n else errs.add('supersedesPostId', 'must be a post uuid');\n }\n\n const questions = list('questionsAnswered', flags.question);\n if (questions !== undefined) {\n validateStringList(questions, 'questionsAnswered', errs);\n card.questionsAnswered = questions;\n }\n const tasks = list('tasksSupported', flags.task);\n if (tasks !== undefined) {\n validateStringList(tasks, 'tasksSupported', errs);\n card.tasksSupported = tasks;\n }\n\n const scope = scalar('scope', flags.scope);\n if (scope !== undefined) {\n if (scope.length > 500) errs.add('scope', 'must be at most 500 characters');\n else card.scope = scope;\n }\n const exclusions = scalar('exclusions', flags.exclusions);\n if (exclusions !== undefined) {\n if (exclusions.length > 500) errs.add('exclusions', 'must be at most 500 characters');\n else card.exclusions = exclusions;\n }\n const provenance = scalar('provenanceSummary', flags.provenance);\n if (provenance !== undefined) {\n if (provenance.length > 500) errs.add('provenanceSummary', 'must be at most 500 characters');\n else card.provenanceSummary = provenance;\n }\n const methodology = scalar('methodologySummary', flags.methodology);\n if (methodology !== undefined) {\n if (methodology.length > 500) errs.add('methodologySummary', 'must be at most 500 characters');\n else card.methodologySummary = methodology;\n }\n\n const appliesTo = flags.appliesTo ?? readAppliesTo(frontmatter, errs);\n if (appliesTo !== undefined) {\n const validated = validateAppliesTo(appliesTo, errs);\n if (validated !== undefined) card.appliesTo = validated;\n }\n\n const cadence = scalar('maintenanceCadence', undefined);\n if (cadence !== undefined) {\n if (cadence.length > 120) errs.add('maintenanceCadence', 'must be at most 120 characters');\n else card.maintenanceCadence = cadence;\n }\n\n const repro = scalar('reproductionMinutes', undefined);\n if (repro !== undefined) {\n const n = Number(repro);\n if (!Number.isInteger(n) || n < 0 || n > 1_000_000) {\n errs.add('reproductionMinutes', 'must be an integer from 0 to 1000000');\n } else {\n card.reproductionMinutes = n;\n }\n }\n\n const cost = scalar('estimatedPaidInputCost', undefined);\n if (cost !== undefined) {\n if (ATOMIC_RE.test(cost)) card.estimatedPaidInputCost = cost;\n else errs.add('estimatedPaidInputCost', 'must be an atomic USDC digit string');\n }\n\n errs.throwIfAny();\n return Object.keys(card).length > 0 ? card : undefined;\n}\n\nfunction validateIso(\n value: string | undefined,\n field: string,\n errs: CardErrors,\n): string | undefined {\n if (value === undefined) return undefined;\n if (!ISO_OFFSET_RE.test(value) || !Number.isFinite(Date.parse(value))) {\n errs.add(field, 'must be an ISO-8601 timestamp with an offset, e.g. 2026-07-01T00:00:00Z');\n return undefined;\n }\n return value;\n}\n\nfunction validateStringList(list: string[], field: string, errs: CardErrors): void {\n if (list.length > 10) errs.add(field, 'at most 10 items');\n for (const item of list) {\n if (item.length === 0) errs.add(field, 'items must be non-empty');\n else if (item.length > 200) errs.add(field, 'each item is at most 200 characters');\n }\n}\n\nfunction readAppliesTo(\n frontmatter: Frontmatter,\n errs: CardErrors,\n): Record<string, string[]> | undefined {\n const fm = frontmatter.appliesTo;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string' || Array.isArray(fm)) {\n errs.add('appliesTo', 'must be a map of key to a list of values');\n return undefined;\n }\n return fm;\n}\n\nfunction validateAppliesTo(\n appliesTo: Record<string, string[]>,\n errs: CardErrors,\n): Record<string, string[]> | undefined {\n const keys = Object.keys(appliesTo);\n if (keys.length > 8) errs.add('appliesTo', 'at most 8 keys');\n const out: Record<string, string[]> = {};\n for (const [key, rawValues] of Object.entries(appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n errs.add('appliesTo', `key ${JSON.stringify(key)} must match ^[a-z][a-z0-9_]{0,31}$`);\n continue;\n }\n const values = rawValues.map((v) => v.trim());\n if (values.length > 20) errs.add('appliesTo', `key ${key} has more than 20 values`);\n for (const v of values) {\n if (v.length < 1 || v.length > 120) {\n errs.add('appliesTo', `key ${key} values must be 1 to 120 characters`);\n }\n }\n out[key] = values;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Parse repeatable `--applies-to k=v` flags into a map (values accumulate per key). */\nexport function parseAppliesToFlags(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const value = pair.slice(eq + 1).trim();\n guardKey(key);\n (out[key] ??= []).push(value);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// The cacheEligible echo: token → plain sentence (spec 09 §4 Q9 rubric).\n// ---------------------------------------------------------------------------\n\nconst MISSING_SENTENCES: Record<string, string> = {\n questionsOrTasks: 'Add at least one question answered or task supported.',\n scope: 'Describe the scope (what this piece covers).',\n exclusions: 'State the exclusions (what this piece does not cover).',\n asOf: 'Set an as-of date (a snapshot card needs one).',\n provenanceOrMethodology: 'Add a provenance or methodology summary.',\n};\n\n/**\n * Map the server's `cacheEligibleMissing` tokens to plain sentences for the\n * receipt. Treats the recomputed `cacheEligibleMissing` as authoritative for what\n * to fix (the stored `cacheEligible` boolean can lag a rubric change); an unknown\n * future token passes through verbatim rather than being dropped.\n */\nexport function missingSentences(tokens: string[]): string[] {\n return tokens.map((t) => MISSING_SENTENCES[t] ?? t);\n}\n\n/**\n * A LOCAL preview of the Q9 eligibility rubric for the pre-publish confirmation\n * payload — the server recomputes the authoritative `cacheEligibleMissing` on\n * write, but the confirmation prompt shows the human what the card is still\n * missing before they approve. `asOf` counts only for a snapshot card.\n */\nexport function localCardEligibility(card: ResourceCardInput | undefined): {\n cacheEligible: boolean;\n missing: string[];\n} {\n const tokens: string[] = [];\n // Parity with the server rubric: presence is trim().length > 0, so a bare\n // `scope:` ('' after parse) or `--scope \" \"` counts as MISSING, not present —\n // otherwise the needs_confirmation preview claims eligible for a card the\n // server will echo ineligible.\n const hasQuestionsOrTasks =\n (card?.questionsAnswered?.some(hasText) ?? false) ||\n (card?.tasksSupported?.some(hasText) ?? false);\n if (!hasQuestionsOrTasks) tokens.push('questionsOrTasks');\n if (!hasText(card?.scope)) tokens.push('scope');\n if (!hasText(card?.exclusions)) tokens.push('exclusions');\n if (card?.temporalMode === 'snapshot' && !hasText(card.asOf)) tokens.push('asOf');\n if (!hasText(card?.provenanceSummary) && !hasText(card?.methodologySummary)) {\n tokens.push('provenanceOrMethodology');\n }\n return { cacheEligible: tokens.length === 0, missing: missingSentences(tokens) };\n}\n\n/** The server's presence rubric: a non-empty value after trimming. */\nfunction hasText(value: string | undefined): boolean {\n return value !== undefined && value.trim().length > 0;\n}\n\nfunction usage(message: string): CliError {\n return new CliError('USAGE', message, {\n fix: 'Frontmatter supports key: value, key: [a, b], block lists, and a one-level appliesTo map.',\n });\n}\n","import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResponse, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { rateLimitError } from './agent-api';\nimport { trimSlash } from './url';\nimport type { ResourceCardInput } from './card';\nimport type { WriteAuth } from './session-key';\n\n/**\n * The owned-post contract: `POST /api/posts` (publish, A3 tenjin#382) plus the\n * owner-scoped `GET`/`PUT /api/posts/<id>` that `edit` reads and merges through.\n *\n * Request building and response validation both live here. The wire shape is\n * validated defensively, and an unknown shape degrades to a CONTRACT_MISMATCH\n * rather than a guess — the same discipline as agent-api.ts, which this models.\n * `POST /api/posts` and `PUT /api/posts/<id>` are each `z.strictObject`\n * server-side, so a body carries ONLY the fields declared below;\n * `cacheEligible`/`cacheEligibleMissing`/`schemaVersion` are server-owned and are\n * never sent. Every write is signed through the injected WriteAuth (a session key\n * by default, plain SIWX as the fallback), and a 401 is recovered per the auth's\n * own rules.\n */\n\n/** The status vocabulary; the as-const source the PublishStatus union derives from. */\nexport const PUBLISH_STATUSES = ['draft', 'published', 'unlisted'] as const;\nexport type PublishStatus = (typeof PUBLISH_STATUSES)[number];\n\nexport interface PublishInput {\n title?: string;\n bodyMd?: string;\n excerpt?: string;\n tags?: string[];\n /** Atomic USDC digit string (converted from the decimal-USD edge upstream). */\n priceAtomic?: string;\n /** First-post-only word-handle claim (POST only). */\n handle?: string;\n status: PublishStatus;\n resource?: ResourceCardInput;\n}\n\n/** The exact strictObject body sent to POST /api/posts (defined keys only). */\nexport interface PostCreateBody {\n title?: string;\n bodyMd?: string;\n excerpt?: string;\n tags?: string[];\n price?: string;\n handle?: string;\n status?: PublishStatus;\n resource?: ResourceCardInput;\n}\n\nconst PRICE_RE = /^(0|[1-9]\\d{0,12})$/;\nconst HANDLE_RE = /^[a-z0-9-]{2,32}$/;\n// A handle the server refuses beyond the charset rule: an address-shaped handle\n// (0x-prefixed) collides with the address form of a creator, and `latest` is the\n// reserved newest-post alias. The full reserved set is server-authoritative — a\n// 400/409 still catches any others — but these two are documented and mirrored.\nconst RESERVED_HANDLES = new Set(['latest']);\n\n/**\n * Assemble + locally validate the create body against the server's bounds so a\n * malformed post fails as USAGE (exit 2) before any network round trip. A\n * non-draft publish requires a title AND body; a draft needs at least one of the\n * two (an all-empty draft is refused, matching the server's superRefine).\n */\nexport function buildPostCreateBody(input: PublishInput): PostCreateBody {\n const isDraft = input.status === 'draft';\n const title = input.title?.trim();\n const bodyMd = input.bodyMd;\n const hasTitle = title !== undefined && title.length > 0;\n const hasBody = bodyMd !== undefined && bodyMd.trim().length > 0;\n\n if (isDraft && !hasTitle && !hasBody) {\n throw new CliError('USAGE', 'A draft needs a title or a body.', {\n fix: 'Add a `title:` or some Markdown; a completely empty draft is rejected.',\n });\n }\n if (!isDraft && !hasTitle) {\n throw new CliError('USAGE', 'A published post needs a title.', {\n fix: 'Add a `title:` to the frontmatter or a leading `# Heading`, or pass --draft.',\n });\n }\n if (!isDraft && !hasBody) {\n throw new CliError('USAGE', 'A published post needs a body.', {\n fix: 'Add Markdown below the frontmatter, or pass --draft.',\n });\n }\n if (title !== undefined && title.length > 200) {\n throw new CliError('USAGE', 'title must be at most 200 characters.');\n }\n if (bodyMd !== undefined && bodyMd.length > 200_000) {\n throw new CliError('USAGE', 'bodyMd must be at most 200000 characters.');\n }\n // Trimmed to match the server's `z.string().trim()`: sending \" x\" for a stored\n // \"x\" would otherwise look like a change on every run and never converge.\n const excerpt = input.excerpt?.trim();\n if (excerpt !== undefined && excerpt.length > 500) {\n throw new CliError('USAGE', 'excerpt must be at most 500 characters.');\n }\n if (input.tags !== undefined) {\n if (input.tags.length > 5) throw new CliError('USAGE', 'at most 5 tags.');\n for (const tag of input.tags) {\n if (tag.length === 0 || tag.length > 50) {\n throw new CliError('USAGE', 'each tag is 1 to 50 characters.');\n }\n }\n }\n if (input.priceAtomic !== undefined && !PRICE_RE.test(input.priceAtomic)) {\n throw new CliError('USAGE', `Invalid price: ${JSON.stringify(input.priceAtomic)}`, {\n fix: 'A price is an atomic USDC integer up to 13 digits, e.g. 100000 for $0.10.',\n });\n }\n if (input.handle !== undefined) {\n if (!HANDLE_RE.test(input.handle)) {\n throw new CliError('USAGE', `Invalid handle: ${JSON.stringify(input.handle)}`, {\n fix: 'A handle is 2 to 32 chars of a-z, 0-9, or hyphen.',\n });\n }\n if (input.handle.startsWith('0x') || RESERVED_HANDLES.has(input.handle)) {\n throw new CliError('USAGE', `Reserved handle: ${JSON.stringify(input.handle)}`, {\n fix: 'Pick a handle that is not 0x-prefixed and not a reserved word (e.g. latest).',\n });\n }\n }\n\n return {\n ...(title !== undefined && title.length > 0 ? { title } : {}),\n ...(bodyMd !== undefined ? { bodyMd } : {}),\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(input.tags !== undefined && input.tags.length > 0 ? { tags: input.tags } : {}),\n ...(input.priceAtomic !== undefined ? { price: input.priceAtomic } : {}),\n ...(input.handle !== undefined ? { handle: input.handle } : {}),\n status: input.status,\n ...(input.resource !== undefined ? { resource: input.resource } : {}),\n };\n}\n\n// The response echo. `.passthrough()` keeps unknown future fields; the CLI reads\n// only what the receipt needs. cacheEligibleMissing is authoritative for \"what to\n// fix\" (the stored cacheEligible boolean can lag a rubric change, per spec 09).\n// The stored card values are typed leniently (nullish) because they are read, not\n// sent: a server that starts omitting one must not turn a working read into a\n// CONTRACT_MISMATCH. Only the two eligibility fields are demanded.\nexport const resourceEchoSchema = z\n .object({\n artifactType: z.string().nullish(),\n mediaType: z.string().nullish(),\n temporalMode: z.string().nullish(),\n asOf: z.string().nullish(),\n validUntil: z.string().nullish(),\n supersedesPostId: z.string().nullish(),\n questionsAnswered: z.array(z.string()).nullish(),\n tasksSupported: z.array(z.string()).nullish(),\n scope: z.string().nullish(),\n exclusions: z.string().nullish(),\n appliesTo: z.record(z.string(), z.array(z.string())).nullish(),\n provenanceSummary: z.string().nullish(),\n methodologySummary: z.string().nullish(),\n maintenanceCadence: z.string().nullish(),\n reproductionMinutes: z.number().nullish(),\n estimatedPaidInputCost: z.string().nullish(),\n cacheEligible: z.boolean(),\n cacheEligibleMissing: z.array(z.string()),\n })\n .passthrough();\n\nexport const ownPostSchema = z\n .object({\n id: z.string(),\n slug: z.string(),\n title: z.string(),\n status: z.string(),\n price: z.string(),\n url: z.string(),\n excerpt: z.string().nullish(),\n bodyMd: z.string().nullish(),\n tags: z.array(z.string()).nullish(),\n warnings: z.array(z.string()).optional(),\n resource: resourceEchoSchema.optional(),\n })\n .passthrough();\n\n/** An owned post as POST/GET/PUT /api/posts[/id] return it (unknown keys kept). */\nexport type OwnPost = z.infer<typeof ownPostSchema>;\n/** The stored answer card on an owned post. */\nexport type OwnPostCard = z.infer<typeof resourceEchoSchema>;\n\nexport interface PublishResult {\n resourceId: string;\n slug: string;\n title: string;\n status: string;\n priceAtomic: string;\n url: string;\n /** Present only when a card was sent (and echoed). */\n cacheEligible?: boolean;\n cacheEligibleMissing: string[];\n /** Server-dropped external image refs (spec: owned-uploads-only). */\n warnings: string[];\n}\n\nexport interface PublishClientOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n}\n\n/** Bounded 401 recovery: the initial attempt plus at most this many re-signs. */\nconst MAX_RECOVERIES = 3;\n\n/**\n * Create + publish a post. Signs each attempt through `auth`; on a 401 it reads\n * the failure code and asks `auth` whether a retry is worthwhile (a stale\n * per-request signature re-signs; an expired delegation re-establishes with one\n * wallet signature; an unbound key does not retry), bounded so a server that\n * always 401s cannot loop.\n */\nexport async function publishPost(\n input: PublishInput,\n auth: WriteAuth,\n opts: PublishClientOptions,\n): Promise<PublishResult> {\n const body = buildPostCreateBody(input);\n const url = `${trimSlash(opts.baseUrl)}/api/posts`;\n // One serialization used for BOTH the Content-Digest and the wire bytes, so the\n // signed digest covers exactly what is sent.\n const bodyStr = JSON.stringify(body);\n\n let recoveries = 0;\n for (;;) {\n const authHeaders = await auth.headersFor({ method: 'POST', url, body: bodyStr });\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER, ...authHeaders },\n jsonBody: body,\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n if (!res.ok) throw writeTransportError(url, res);\n\n if (res.status === 401 && recoveries < MAX_RECOVERIES) {\n const code = auth401Code(res);\n if (await auth.recover(code)) {\n recoveries++;\n continue;\n }\n throw authError(code, res);\n }\n if (res.status === 401) throw authError(auth401Code(res), res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 201 && res.status !== 200) throw publishFailed(res);\n\n const parsed = ownPostSchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError('CONTRACT_MISMATCH', 'The publish response did not match the contract.', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n const post = parsed.data;\n return {\n resourceId: post.id,\n slug: post.slug,\n title: post.title,\n status: post.status,\n priceAtomic: post.price,\n url: post.url,\n ...(post.resource !== undefined ? { cacheEligible: post.resource.cacheEligible } : {}),\n cacheEligibleMissing: post.resource?.cacheEligibleMissing ?? [],\n warnings: post.warnings ?? [],\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// The owner-scoped read + merge-update surface (`GET`/`PUT /api/posts/<id>`).\n// ---------------------------------------------------------------------------\n\n/**\n * The card as an update sends it: the create shape plus the explicit-null clears\n * the server's merge accepts on its nullable scalars. Containers clear with an\n * empty `[]`/`{}` rather than null, so their types are unchanged. Field-level\n * merge: an omitted key keeps the stored value, and an array REPLACES wholesale.\n */\nexport type ResourceCardUpdate = Omit<\n ResourceCardInput,\n | 'asOf'\n | 'validUntil'\n | 'supersedesPostId'\n | 'scope'\n | 'exclusions'\n | 'provenanceSummary'\n | 'methodologySummary'\n | 'maintenanceCadence'\n | 'reproductionMinutes'\n | 'estimatedPaidInputCost'\n> & {\n asOf?: string | null;\n validUntil?: string | null;\n supersedesPostId?: string | null;\n scope?: string | null;\n exclusions?: string | null;\n provenanceSummary?: string | null;\n methodologySummary?: string | null;\n maintenanceCadence?: string | null;\n reproductionMinutes?: number | null;\n estimatedPaidInputCost?: string | null;\n};\n\nexport interface PostUpdateInput {\n title?: string;\n bodyMd?: string;\n excerpt?: string;\n tags?: string[];\n /** Atomic USDC digit string (converted from the decimal-USD edge upstream). */\n priceAtomic?: string;\n status?: PublishStatus;\n resource?: ResourceCardUpdate;\n}\n\n/** The exact strictObject body sent to PUT /api/posts/<id> (defined keys only). */\nexport interface PostUpdateBody {\n title?: string;\n bodyMd?: string;\n excerpt?: string;\n tags?: string[];\n price?: string;\n status?: PublishStatus;\n resource?: ResourceCardUpdate;\n}\n\n/**\n * Assemble + locally validate the update body against the server's bounds, the\n * partial-update twin of buildPostCreateBody: every field is optional (an omitted\n * key keeps the stored value), so the create-only \"a published post needs a title\n * and a body\" rules do not apply — but an EMPTY title or body would blank a live\n * post, which the top-level fields cannot express a clear for, so both are refused\n * as USAGE. `handle` is create-only and has no PostUpdate counterpart.\n */\nexport function buildPostUpdateBody(input: PostUpdateInput): PostUpdateBody {\n const title = input.title?.trim();\n if (input.title !== undefined && (title === undefined || title.length === 0)) {\n throw new CliError('USAGE', 'title cannot be empty.', {\n fix: 'Pass a title, or omit --title to keep the stored one.',\n });\n }\n if (title !== undefined && title.length > 200) {\n throw new CliError('USAGE', 'title must be at most 200 characters.');\n }\n if (input.bodyMd !== undefined) {\n if (input.bodyMd.trim().length === 0) {\n throw new CliError('USAGE', 'bodyMd cannot be empty.', {\n fix: 'Pass a file with Markdown in it, or omit --body to keep the stored body.',\n });\n }\n if (input.bodyMd.length > 200_000) {\n throw new CliError('USAGE', 'bodyMd must be at most 200000 characters.');\n }\n }\n // Trimmed to match the server's `z.string().trim()`: sending \" x\" for a stored\n // \"x\" would otherwise look like a change on every run and never converge.\n const excerpt = input.excerpt?.trim();\n if (excerpt !== undefined && excerpt.length > 500) {\n throw new CliError('USAGE', 'excerpt must be at most 500 characters.');\n }\n if (input.tags !== undefined) {\n if (input.tags.length > 5) throw new CliError('USAGE', 'at most 5 tags.');\n for (const tag of input.tags) {\n if (tag.length === 0 || tag.length > 50) {\n throw new CliError('USAGE', 'each tag is 1 to 50 characters.');\n }\n }\n }\n if (input.priceAtomic !== undefined && !PRICE_RE.test(input.priceAtomic)) {\n throw new CliError('USAGE', `Invalid price: ${JSON.stringify(input.priceAtomic)}`, {\n fix: 'A price is an atomic USDC integer up to 13 digits, e.g. 100000 for $0.10.',\n });\n }\n\n const body: PostUpdateBody = {\n ...(title !== undefined ? { title } : {}),\n ...(input.bodyMd !== undefined ? { bodyMd: input.bodyMd } : {}),\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(input.tags !== undefined ? { tags: input.tags } : {}),\n ...(input.priceAtomic !== undefined ? { price: input.priceAtomic } : {}),\n ...(input.status !== undefined ? { status: input.status } : {}),\n ...(input.resource !== undefined ? { resource: input.resource } : {}),\n };\n // An empty PUT would burn a nonce to change nothing; the caller is expected to\n // route \"no change flags\" to the read path instead.\n if (Object.keys(body).length === 0) {\n throw new CliError('USAGE', 'Nothing to update.', {\n fix: 'Pass at least one field flag, or run `tenjin edit <postId>` with no flags to view the post.',\n });\n }\n return body;\n}\n\n/**\n * Read one of your own posts (`GET /api/posts/<id>`). Owner-scoped, so it is\n * signed through the same WriteAuth the writes use, but it is a READ: it sends no\n * body, burns no nonce, and its failures are runtime-class (exit 1), never the\n * post-approval write class.\n */\nexport async function getOwnPost(\n id: string,\n auth: WriteAuth,\n opts: PublishClientOptions,\n): Promise<OwnPost> {\n const url = `${trimSlash(opts.baseUrl)}/api/posts/${encodeURIComponent(id)}`;\n\n let recoveries = 0;\n for (;;) {\n const authHeaders = await auth.headersFor({ method: 'GET', url });\n const res = await httpRequest(url, {\n method: 'GET',\n timeoutMs: opts.timeoutMs,\n headers: { accept: 'application/json', 'x-tenjin-client': CLIENT_HEADER, ...authHeaders },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n if (!res.ok) throw writeTransportError(url, res);\n\n if (res.status === 401 && recoveries < MAX_RECOVERIES) {\n const code = auth401Code(res);\n if (await auth.recover(code)) {\n recoveries++;\n continue;\n }\n throw readAuthError(code, res);\n }\n if (res.status === 401) throw readAuthError(auth401Code(res), res);\n if (res.status === 404) throw postNotFound(id);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverMessage(res.json) ?? `Could not read post ${id} (${res.status}).`,\n {\n fix: 'Review the server error, then retry.',\n details: { status: res.status, ...(res.json !== undefined ? { server: res.json } : {}) },\n },\n );\n }\n return parseOwnPost(res.json, 'read');\n }\n}\n\n/**\n * Merge-update one of your own posts (`PUT /api/posts/<id>`). Identical signing\n * and 401-recovery discipline to publishPost: every attempt is signed fresh,\n * because each PUT burns a single-use nonce.\n *\n * Failure posture is publish's with one deliberate exception. A rejected write\n * after the caller approved it is exit 4 (the settlement class), but a 404 is\n * exit 1: the post does not exist or is not ours, so the write definitively did\n * not land, and nothing about it is a half-completed operation.\n */\nexport async function updatePost(\n id: string,\n input: PostUpdateInput,\n auth: WriteAuth,\n opts: PublishClientOptions,\n): Promise<OwnPost> {\n const body = buildPostUpdateBody(input);\n const url = `${trimSlash(opts.baseUrl)}/api/posts/${encodeURIComponent(id)}`;\n // One serialization for BOTH the Content-Digest and the wire bytes.\n const bodyStr = JSON.stringify(body);\n\n let recoveries = 0;\n for (;;) {\n const authHeaders = await auth.headersFor({ method: 'PUT', url, body: bodyStr });\n const res = await httpRequest(url, {\n method: 'PUT',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER, ...authHeaders },\n jsonBody: body,\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n if (!res.ok) throw writeTransportError(url, res);\n\n if (res.status === 401 && recoveries < MAX_RECOVERIES) {\n const code = auth401Code(res);\n if (await auth.recover(code)) {\n recoveries++;\n continue;\n }\n throw authError(code, res);\n }\n if (res.status === 401) throw authError(auth401Code(res), res);\n if (res.status === 404) throw postNotFound(id);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) throw updateFailed(res);\n\n return parseOwnPost(res.json, 'update');\n }\n}\n\nfunction parseOwnPost(json: unknown, what: 'read' | 'update'): OwnPost {\n const parsed = ownPostSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The post ${what} response did not match the contract.`,\n {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data;\n}\n\n/** 404 is deliberately ambiguous server-side (missing vs not yours); say both. */\nfunction postNotFound(id: string): CliError {\n return new CliError('RESOURCE_NOT_FOUND', `Post ${id} was not found, or is not yours.`, {\n fix: 'Check the post id on your desk; owner-scoped routes do not distinguish the two.',\n });\n}\n\n/** A 401 on the READ never wrote anything, so it is runtime-class, not exit 4. */\nfunction readAuthError(code: string | undefined, res: HttpResponse): CliError {\n return new CliError(\n 'API_UNREACHABLE',\n serverMessage(res.json) ?? `Reading the post was not authorized (${code ?? '401'}).`,\n {\n fix:\n code === 'session_key_unbound'\n ? 'Delete ~/.tenjin/session.json to re-establish the session key.'\n : 'Check the wallet and retry.',\n details: {\n code: code ?? 'unauthorized',\n ...(res.json !== undefined ? { server: res.json } : {}),\n },\n },\n );\n}\n\n/**\n * A failed update after approval (exit 4). A `validation_failed` carries dotted\n * field keys (`resource.asOf`, `title`); name them in the message, because the\n * server's own message says only \"validation failed\".\n */\nfunction updateFailed(res: HttpResponse): CliError {\n const fields = fieldErrorKeys(res.json);\n const base = serverMessage(res.json) ?? `Update failed (${res.status}).`;\n return new CliError(\n 'PUBLISH_FAILED',\n fields.length > 0 ? `${base} (${fields.join(', ')})` : base,\n {\n fix:\n fields.length > 0\n ? 'Correct the reported fields, then re-run `tenjin edit`.'\n : 'Review the server error, then re-run `tenjin edit`.',\n details: { status: res.status, ...(res.json !== undefined ? { server: res.json } : {}) },\n },\n );\n}\n\n/** The dotted keys of `error.details.fieldErrors`, when the server sent any. */\nfunction fieldErrorKeys(json: unknown): string[] {\n if (typeof json !== 'object' || json === null) return [];\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return [];\n const details = (err as { details?: unknown }).details;\n if (typeof details !== 'object' || details === null) return [];\n const fieldErrors = (details as { fieldErrors?: unknown }).fieldErrors;\n if (typeof fieldErrors !== 'object' || fieldErrors === null) return [];\n return Object.keys(fieldErrors);\n}\n\n/** The 401 failure code, from WWW-Authenticate `error=\"...\"` then the body code. */\nfunction auth401Code(res: HttpResponse): string | undefined {\n const header = res.header('www-authenticate');\n const m = header !== undefined ? /error=\"([^\"]+)\"/.exec(header) : null;\n if (m?.[1] !== undefined) return m[1];\n return bodyErrorCode(res.json);\n}\n\nfunction bodyErrorCode(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const err = (json as { error?: unknown }).error;\n if (typeof err === 'object' && err !== null) {\n const code = (err as { code?: unknown }).code;\n if (typeof code === 'string') return code;\n }\n }\n return undefined;\n}\n\nfunction serverMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const err = (json as { error?: unknown }).error;\n if (typeof err === 'object' && err !== null) {\n const m = (err as { message?: unknown }).message;\n if (typeof m === 'string') return m;\n }\n }\n return undefined;\n}\n\nfunction authError(code: string | undefined, res: HttpResponse): CliError {\n return new CliError(\n 'PUBLISH_FAILED',\n serverMessage(res.json) ?? `Publish was not authorized (${code ?? '401'}).`,\n {\n fix:\n code === 'session_key_unbound'\n ? 'Delete ~/.tenjin/session.json to re-establish the session key.'\n : 'Check the wallet and retry.',\n details: {\n code: code ?? 'unauthorized',\n ...(res.json !== undefined ? { server: res.json } : {}),\n },\n },\n );\n}\n\n/** Any non-recoverable non-2xx after approval is a write failure (exit 4). */\nfunction publishFailed(res: HttpResponse): CliError {\n return new CliError(\n 'PUBLISH_FAILED',\n serverMessage(res.json) ?? `Publish failed (${res.status}).`,\n {\n fix: 'Review the server error, then re-run `tenjin publish`.',\n details: { status: res.status, ...(res.json !== undefined ? { server: res.json } : {}) },\n },\n );\n}\n\n/** A transport/timeout failure never reached the write; a network-class error. */\nfunction writeTransportError(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n","import { createSessionKeyAuth, createSiwxAuth, SESSION_CHAIN_ID } from './session-key';\nimport type { SessionScope, WriteAuth } from './session-key';\nimport type { PublishMode } from './config';\nimport { PublishModeSchema } from './config';\nimport type { ResolvedPublishSettings } from './settings';\nimport type { ScanFinding } from './scan';\nimport type { TenjinSigner } from './wallet';\n\n/**\n * The consent layer both writing commands share (`publish` and `edit`): the write\n * auth they sign through, the publish.mode gate, the stderr mode notices, and the\n * scan-finding shaping their refusal payloads carry. It lives here because the two\n * commands must gate IDENTICALLY — an edit ships content to the same public page a\n * publish does — and a second copy of a gate is a gate that drifts.\n */\n\n/**\n * Writes require Base mainnet per the server's SIWX chain constraint. Aliased to\n * the one session chain id rather than re-declared: `tenjin session start` mints\n * into the same `session.json` this path reuses, and two constants that drifted\n * would silently invalidate each other's cached delegation.\n */\nexport const WRITE_CHAIN_ID = SESSION_CHAIN_ID;\n\nexport interface WriteAuthOptions {\n signer: TenjinSigner;\n baseUrl: string;\n dataDir: string;\n /**\n * Least privilege for what this run will do: 'read' for an owner-scoped read,\n * 'read+write' for anything that writes. A cached wider session still satisfies\n * a narrower need, so asking for 'read' costs no extra wallet signature.\n */\n scope: SessionScope;\n /** Force the plain-SIWX path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n env: NodeJS.ProcessEnv;\n}\n\n/**\n * The write-auth seam: a session key by default (one wallet signature per session,\n * then P-256 signatures per request), the plain-SIWX fallback when sessions are\n * disabled.\n */\nexport function resolveWriteAuth(opts: WriteAuthOptions): WriteAuth {\n const config = {\n signer: opts.signer,\n baseUrl: opts.baseUrl,\n chainId: WRITE_CHAIN_ID,\n dataDir: opts.dataDir,\n scope: opts.scope,\n };\n const useSession = opts.useSession ?? opts.env.TENJIN_NO_SESSION !== '1';\n return useSession ? createSessionKeyAuth(config) : createSiwxAuth(config);\n}\n\n/**\n * The consent gate (D38): review always asks; auto asks only on a soft finding;\n * full-auto proceeds past soft findings. A hard block is NOT here — it refuses in\n * every mode and is never reachable by consent.\n */\nexport function needsConfirmation(mode: PublishMode, warnCount: number): boolean {\n return mode === 'review' || (mode === 'auto' && warnCount > 0);\n}\n\n/**\n * The stderr notices that accompany a resolved mode: the resolver's own downgrade\n * warnings, a mistyped TENJIN_PUBLISH_MODE (which the resolver otherwise discards\n * silently), and a one-line explainer when the mode was never configured, so an\n * unconfigured write is never a silent surprise. `defaultExplainer` is the\n * command's own phrasing of what the default does.\n */\nexport function writeModeNotices(\n stderr: NodeJS.WritableStream,\n settings: ResolvedPublishSettings,\n env: NodeJS.ProcessEnv,\n defaultExplainer: string,\n): void {\n for (const warning of settings.warnings) {\n stderr.write(`${warning}\\n`);\n }\n const envMode = env.TENJIN_PUBLISH_MODE;\n if (\n envMode !== undefined &&\n envMode.length > 0 &&\n !PublishModeSchema.safeParse(envMode).success\n ) {\n stderr.write(\n `Ignoring invalid TENJIN_PUBLISH_MODE=${JSON.stringify(envMode)}; using ${settings.mode} (${settings.modeSource}).\\n`,\n );\n }\n if (settings.modeSource === 'default') {\n stderr.write(\n `publish.mode: ${settings.mode} (default) - ${defaultExplainer}: tenjin config set publish.mode auto.\\n`,\n );\n }\n}\n\n/** A finding safe to echo: block excerpts are already masked by the scanner. */\nexport function publicFinding(f: ScanFinding): {\n check: string;\n severity: string;\n line: number;\n excerpt: string;\n} {\n return { check: f.check, severity: f.severity, line: f.line, excerpt: f.excerpt };\n}\n\n/**\n * Collapse findings that share a check + excerpt to one, keeping the first. The\n * same value scanned twice (a frontmatter field present in both the raw file and\n * the derived card) is one finding, not two.\n */\nexport function dedupeFindings(findings: ScanFinding[]): ScanFinding[] {\n const seen = new Set<string>();\n return findings.filter((f) => {\n const key = `${f.check}:${f.excerpt}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** \"N secret finding(s) (check, check)\" — the shared half of both block messages. */\nexport function describeFindings(blocking: ScanFinding[]): string {\n const checks = [...new Set(blocking.map((f) => f.check))].join(', ');\n return `${blocking.length} secret finding(s) (${checks})`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAM,mBAAmB;AAElB,SAAS,KAAK,MAAc,UAAuB,CAAC,GAAkB;AAC3E,QAAM,QAAQ,KAAK,MA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M;AACN,aAAW,WAAW,SAAS,UAAU;AACvC,WAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AAAA,EAC7B;AACA,QAAM,UAAU,IAAI;AACpB,MACE,YAAY,UACZ,QAAQ,SAAS,KACjB,CAAC,kBAAkB,UAAU,OAAO,EAAE,SACtC;AACA,WAAO;AAAA,MACL,wCAAwC,KAAK,UAAU,OAAO,CAAC,WAAW,SAAS,IAAI,KAAK,SAAS,UAAU;AAAA;AAAA,IACjH;AAAA,EACF;AACA,MAAI,SAAS,eAAe,WAAW;AACrC,WAAO;AAAA,MACL,iBAAiB,SAAS,IAAI,gBAAgB,gBAAgB;AAAA;AAAA,IAChE;AAAA,EACF;AACF;AAGO,SAAS,cAAc,GAK5B;AACA,SAAO,EAAE,OAAO,EAAE,OAAO,UAAU,EAAE,UAAU,MAAM,EAAE,MAAM,SAAS,EAAE,QAAQ;AAClF;AAOO,SAAS,eAAe,UAAwC;AACrE,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,SAAS,OAAO,CAAC,MAAM;AAC5B,UAAM,MAAM,GAAG,EAAE,KAAK,IAAI,EAAE,OAAO;AACnC,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AACZ,WAAO;AAAA,EACT,CAAC;AACH;AAGO,SAAS,iBAAiB,UAAiC;AAChE,QAAM,SAAS,CAAC,GAAG,IAAI,IAAI,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,EAAE,KAAK,IAAI;AACnE,SAAO,GAAG,SAAS,MAAM,uBAAuB,MAAM;AACxD;","names":[]}
@@ -3,11 +3,9 @@ import {
3
3
  withFileLock
4
4
  } from "./chunk-YBMMV4Y4.js";
5
5
  import {
6
+ external_exports,
6
7
  writeFileAtomic
7
- } from "./chunk-2JQ5JSG6.js";
8
- import {
9
- external_exports
10
- } from "./chunk-PAUXMRSF.js";
8
+ } from "./chunk-J6CVKC4M.js";
11
9
 
12
10
  // src/lib/search-store.ts
13
11
  import { mkdir, readFile } from "fs/promises";
@@ -93,4 +91,4 @@ export {
93
91
  findStoredCandidate,
94
92
  findSearchForResource
95
93
  };
96
- //# sourceMappingURL=chunk-CVX6JNGD.js.map
94
+ //# sourceMappingURL=chunk-OTDI5FXG.js.map
@@ -1 +1 @@
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\nconst MAX_ENTRIES = 50;\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\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});\nexport type StoredSearch = z.infer<typeof StoredSearchSchema>;\n\nconst StoreSchema = z.object({\n schemaVersion: z.literal(1),\n searches: z.array(StoredSearchSchema),\n});\n\nfunction storePath(dataDir: string): string {\n return join(dataDir, 'searches.json');\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/** Prepend a search (newest first), cap to MAX_ENTRIES, 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 = [entry, ...existing.filter((l) => l.searchId !== entry.searchId)].slice(\n 0,\n MAX_ENTRIES,\n );\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n });\n}\n\nexport async function latestSearch(dataDir: string): Promise<StoredSearch | null> {\n const searches = await loadSearches(dataDir);\n return searches[0] ?? 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;AAarB,IAAM,cAAc;AAEpB,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;AAGD,IAAM,qBAAqB,iBAAE,OAAO;AAAA,EAClC,UAAU,iBAAE,OAAO;AAAA,EACnB,IAAI,iBAAE,OAAO;AAAA,EACb,UAAU,iBAAE,OAAO;A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AAGA,eAAsB,oBACpB,SACA,YACiC;AACjC,aAAW,UAAU,MAAM,aAAa,OAAO,GAAG;AAChD,UAAM,MAAM,OAAO,WAAW,KAAK,CAAC,MAAM,EAAE,eAAe,UAAU;AACrE,QAAI,IAAK,QAAO;AAAA,EAClB;AACA,SAAO;AACT;AAIA,eAAsB,sBACpB,SACA,OACwB;AACxB,aAAW,UAAU,MAAM,aAAa,OAAO,GAAG;AAChD,UAAM,MAAM,OAAO,WAAW;AAAA,MAC5B,CAAC,MACE,MAAM,eAAe,UAAa,EAAE,eAAe,MAAM,cACzD,MAAM,QAAQ,UAAa,EAAE,QAAQ,MAAM;AAAA,IAChD;AACA,QAAI,IAAK,QAAO,OAAO;AAAA,EACzB;AACA,SAAO;AACT;","names":[]}
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\nconst MAX_ENTRIES = 50;\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\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});\nexport type StoredSearch = z.infer<typeof StoredSearchSchema>;\n\nconst StoreSchema = z.object({\n schemaVersion: z.literal(1),\n searches: z.array(StoredSearchSchema),\n});\n\nfunction storePath(dataDir: string): string {\n return join(dataDir, 'searches.json');\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/** Prepend a search (newest first), cap to MAX_ENTRIES, 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 = [entry, ...existing.filter((l) => l.searchId !== entry.searchId)].slice(\n 0,\n MAX_ENTRIES,\n );\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n });\n}\n\nexport async function latestSearch(dataDir: string): Promise<StoredSearch | null> {\n const searches = await loadSearches(dataDir);\n return searches[0] ?? 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;AAarB,IAAM,cAAc;AAEpB,IAAM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;AAAA,MACJ,UAAU,OAAO;AAAA,MACjB,GAAG,KAAK,UAAU,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC,CAAC;AAAA;AAAA,MAC1D,EAAE,MAAM,KAAO,SAAS,IAAM;AAAA,IAChC;AAAA,EACF,CAAC;AACH;AAEA,eAAsB,aAAa,SAA+C;AAChF,QAAM,WAAW,MAAM,aAAa,OAAO;AAC3C,SAAO,SAAS,CAAC,KAAK;AACxB;AAGA,eAAsB,oBACpB,SACA,YACiC;AACjC,aAAW,UAAU,MAAM,aAAa,OAAO,GAAG;AAChD,UAAM,MAAM,OAAO,WAAW,KAAK,CAAC,MAAM,EAAE,eAAe,UAAU;AACrE,QAAI,IAAK,QAAO;AAAA,EAClB;AACA,SAAO;AACT;AAIA,eAAsB,sBACpB,SACA,OACwB;AACxB,aAAW,UAAU,MAAM,aAAa,OAAO,GAAG;AAChD,UAAM,MAAM,OAAO,WAAW;AAAA,MAC5B,CAAC,MACE,MAAM,eAAe,UAAa,EAAE,eAAe,MAAM,cACzD,MAAM,QAAQ,UAAa,EAAE,QAAQ,MAAM;AAAA,IAChD;AACA,QAAI,IAAK,QAAO,OAAO;AAAA,EACzB;AACA,SAAO;AACT;","names":[]}
@@ -5,13 +5,15 @@ import {
5
5
  } from "./chunk-WWX32ML4.js";
6
6
  import {
7
7
  CLIENT_HEADER,
8
- httpRequest,
8
+ httpRequest
9
+ } from "./chunk-URSGGRO4.js";
10
+ import {
9
11
  trimSlash
10
- } from "./chunk-ZDY2KY5X.js";
12
+ } from "./chunk-XBJ3VLWX.js";
11
13
  import {
12
14
  CliError,
13
15
  external_exports
14
- } from "./chunk-PAUXMRSF.js";
16
+ } from "./chunk-J6CVKC4M.js";
15
17
 
16
18
  // src/lib/agent-api.ts
17
19
  var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
@@ -317,4 +319,4 @@ export {
317
319
  buildOutcomeItem,
318
320
  postOutcomes
319
321
  };
320
- //# sourceMappingURL=chunk-3IRDP7TN.js.map
322
+ //# sourceMappingURL=chunk-P3FBESBB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBA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AK,OAAM,eAAe,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;AAGtE,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,IAAI,IAAI,KAAK,0BAA0B,IAAI,MAAM;AAAA,MACpE;AAAA,QACE,KAAK;AAAA,QACL,SAAS,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,QAAM,WACJ,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,QAAQ,cAAc,IAAI,OACnE,OAAQ,IAAI,KAA+B,QAAQ,IACnD,MAAM;AACZ,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
1
+ {"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,MAAM,aAAa,UAAa,CAAC,UAAU,KAAK,MAAM,QAAQ,GAAG;AACnE,UAAM,IAAI,SAAS,SAAS,wBAAwB,KAAK,UAAU,MAAM,QAAQ,CAAC,IAAI;AAAA,MACpF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,QAAQ,MAAM,SAAS;AAC7B,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,QAAQ,WAAW;AAC9D,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,MAAM,KAAK,CAAC,IAAI;AAAA,MAC7E,KAAK,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