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

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 (157) hide show
  1. package/README.md +322 -197
  2. package/dist/{_esm-FEASBWRP.js → _esm-N4KAVXQR.js} +9 -9
  3. package/dist/buy-YMXXVNFH.js +42 -0
  4. package/dist/candidate-H7FR4AU5.js +22 -0
  5. package/dist/{ccip-XR5NE5QK.js → ccip-RPPPKTJR.js} +5 -5
  6. package/dist/{ccip-NQXCEK2U.js → ccip-ZGGWQN4X.js} +4 -4
  7. package/dist/{chunk-MUBUQVC3.js → chunk-2JQ5JSG6.js} +3 -2
  8. package/dist/{chunk-MUBUQVC3.js.map → chunk-2JQ5JSG6.js.map} +1 -1
  9. package/dist/{chunk-662MSGZB.js → chunk-3IRDP7TN.js} +100 -66
  10. package/dist/chunk-3IRDP7TN.js.map +1 -0
  11. package/dist/{chunk-YALGASEU.js → chunk-47PP7TAG.js} +1610 -1610
  12. package/dist/chunk-47PP7TAG.js.map +1 -0
  13. package/dist/{buy-EE6SEXP6.js → chunk-4WVKXKDK.js} +27 -59
  14. package/dist/chunk-4WVKXKDK.js.map +1 -0
  15. package/dist/chunk-5SCU253N.js +412 -0
  16. package/dist/chunk-5SCU253N.js.map +1 -0
  17. package/dist/{chunk-UGX7YPX2.js → chunk-7FK2UN2T.js} +65 -65
  18. package/dist/{chunk-UGX7YPX2.js.map → chunk-7FK2UN2T.js.map} +1 -1
  19. package/dist/chunk-ADJYSM45.js +135 -0
  20. package/dist/chunk-ADJYSM45.js.map +1 -0
  21. package/dist/{chunk-DXTQ3CSI.js → chunk-BIKAUVC2.js} +43 -11
  22. package/dist/chunk-BIKAUVC2.js.map +1 -0
  23. package/dist/{chunk-Z6MFJV5Z.js → chunk-C444K6MI.js} +266 -55
  24. package/dist/chunk-C444K6MI.js.map +1 -0
  25. package/dist/{chunk-JPHG2JW3.js → chunk-CVX6JNGD.js} +26 -26
  26. package/dist/chunk-CVX6JNGD.js.map +1 -0
  27. package/dist/{chunk-S3IGX57D.js → chunk-FU6MCSLG.js} +9 -9
  28. package/dist/{lookup-ZPN2Q67N.js → chunk-HTDALK7M.js} +46 -32
  29. package/dist/chunk-HTDALK7M.js.map +1 -0
  30. package/dist/chunk-IOPWPMT2.js +239 -0
  31. package/dist/chunk-IOPWPMT2.js.map +1 -0
  32. package/dist/{chunk-5CLSD5YN.js → chunk-KYQVEKP5.js} +7 -7
  33. package/dist/{chunk-RRN3YTK7.js → chunk-KZAAWQNP.js} +3 -3
  34. package/dist/{chunk-7KUW4MJD.js → chunk-L4IHCN6B.js} +11 -7
  35. package/dist/chunk-L4IHCN6B.js.map +1 -0
  36. package/dist/{chunk-XHC6FCGZ.js → chunk-LAM66WFJ.js} +25 -11
  37. package/dist/chunk-LAM66WFJ.js.map +1 -0
  38. package/dist/{chunk-NCE5NSN6.js → chunk-M2O56UK7.js} +158 -158
  39. package/dist/chunk-M2O56UK7.js.map +1 -0
  40. package/dist/{chunk-GO75V3NZ.js → chunk-MDDGEGSW.js} +8 -6
  41. package/dist/chunk-MDDGEGSW.js.map +1 -0
  42. package/dist/{chunk-XJIW7USF.js → chunk-MJZZTKCC.js} +112 -6
  43. package/dist/chunk-MJZZTKCC.js.map +1 -0
  44. package/dist/{chunk-Z52RA3NC.js → chunk-NFSOVL3C.js} +51 -21
  45. package/dist/chunk-NFSOVL3C.js.map +1 -0
  46. package/dist/{chunk-FJPLRISB.js → chunk-NJF2WENW.js} +5 -4
  47. package/dist/chunk-NJF2WENW.js.map +1 -0
  48. package/dist/{chunk-OYMYCW7J.js → chunk-PAUXMRSF.js} +45 -4
  49. package/dist/{chunk-OYMYCW7J.js.map → chunk-PAUXMRSF.js.map} +1 -1
  50. package/dist/{chunk-ZABPQJ3M.js → chunk-POJRB2AE.js} +2 -2
  51. package/dist/{publish-BKBQQAW4.js → chunk-PYNSGYBE.js} +254 -57
  52. package/dist/chunk-PYNSGYBE.js.map +1 -0
  53. package/dist/{chunk-YN5SHIXQ.js → chunk-QONTBYQW.js} +12 -9
  54. package/dist/chunk-QONTBYQW.js.map +1 -0
  55. package/dist/chunk-QW2Q2KAH.js +27 -0
  56. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  57. package/dist/chunk-RTJLLPFA.js +599 -0
  58. package/dist/chunk-RTJLLPFA.js.map +1 -0
  59. package/dist/{chunk-CYOF7ROH.js → chunk-S5RYMCV6.js} +3 -3
  60. package/dist/chunk-TXPPMK4L.js +59 -0
  61. package/dist/chunk-TXPPMK4L.js.map +1 -0
  62. package/dist/{chunk-ZMHYXMO6.js → chunk-U5S527PP.js} +3 -3
  63. package/dist/{chunk-RY4XKNV3.js → chunk-UHTVXQ2O.js} +3 -3
  64. package/dist/{chunk-QVX5MWJZ.js → chunk-W6R3HAAG.js} +2 -2
  65. package/dist/{chunk-3OV7E5G5.js → chunk-WWX32ML4.js} +1 -1
  66. package/dist/{chunk-3OV7E5G5.js.map → chunk-WWX32ML4.js.map} +1 -1
  67. package/dist/{chunk-HIVZG55D.js → chunk-XJN5WUKL.js} +2 -2
  68. package/dist/{chunk-HSDCI7OV.js → chunk-YLYINX2H.js} +3 -3
  69. package/dist/{chunk-4ONXEEQL.js → chunk-ZDY2KY5X.js} +2 -2
  70. package/dist/{chunk-4ONXEEQL.js.map → chunk-ZDY2KY5X.js.map} +1 -1
  71. package/dist/{chunk-TLCMMYLY.js → chunk-ZIYVN4CD.js} +6 -6
  72. package/dist/chunk-ZIYVN4CD.js.map +1 -0
  73. package/dist/{candidate-ERMSYYQZ.js → chunk-ZW3B5LWX.js} +15 -19
  74. package/dist/{candidate-ERMSYYQZ.js.map → chunk-ZW3B5LWX.js.map} +1 -1
  75. package/dist/{cli-SBXI5AMS.js → cli-IW76QTN3.js} +64 -40
  76. package/dist/{cli-SBXI5AMS.js.map → cli-IW76QTN3.js.map} +1 -1
  77. package/dist/{config-VELDKLHY.js → config-VCOS7P5K.js} +8 -6
  78. package/dist/{doctor-T3KWNNP2.js → doctor-WS65JG3V.js} +9 -8
  79. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-WHYKB6HA.js} +5 -5
  80. package/dist/index.js +1 -1
  81. package/dist/inspect-SFJWUQHO.js +33 -0
  82. package/dist/install-RVPQPCKH.js +589 -0
  83. package/dist/install-RVPQPCKH.js.map +1 -0
  84. package/dist/outcome-GNYCSZ7J.js +20 -0
  85. package/dist/publish-DSFWQRUN.js +36 -0
  86. package/dist/publish-DSFWQRUN.js.map +1 -0
  87. package/dist/run-OMPKA43G.js +16807 -0
  88. package/dist/run-OMPKA43G.js.map +1 -0
  89. package/dist/search-KOI6Y7P6.js +24 -0
  90. package/dist/search-KOI6Y7P6.js.map +1 -0
  91. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-XRPVBC6V.js} +3 -3
  92. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  93. package/dist/send-3G4C64HJ.js +222 -0
  94. package/dist/send-3G4C64HJ.js.map +1 -0
  95. package/dist/usdc-4VCDHFWX.js +38 -0
  96. package/dist/usdc-4VCDHFWX.js.map +1 -0
  97. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-TUQJBMHM.js} +5 -5
  98. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  99. package/dist/wallet-B7KJS2R5.js +40 -0
  100. package/dist/wallet-B7KJS2R5.js.map +1 -0
  101. package/dist/wallet-PP22LAX7.js +31 -0
  102. package/dist/wallet-PP22LAX7.js.map +1 -0
  103. package/package.json +4 -3
  104. package/skills/tenjin/SKILL.md +83 -15
  105. package/skills/tenjin-publish/SKILL.md +118 -18
  106. package/skills/tenjin-search/SKILL.md +149 -31
  107. package/dist/buy-EE6SEXP6.js.map +0 -1
  108. package/dist/chunk-662MSGZB.js.map +0 -1
  109. package/dist/chunk-7KUW4MJD.js.map +0 -1
  110. package/dist/chunk-AWPAWHNX.js +0 -333
  111. package/dist/chunk-AWPAWHNX.js.map +0 -1
  112. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  113. package/dist/chunk-ESPNTPQ2.js +0 -207
  114. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  115. package/dist/chunk-FJPLRISB.js.map +0 -1
  116. package/dist/chunk-GO75V3NZ.js.map +0 -1
  117. package/dist/chunk-JPHG2JW3.js.map +0 -1
  118. package/dist/chunk-NCE5NSN6.js.map +0 -1
  119. package/dist/chunk-TLCMMYLY.js.map +0 -1
  120. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  121. package/dist/chunk-XJIW7USF.js.map +0 -1
  122. package/dist/chunk-YALGASEU.js.map +0 -1
  123. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  124. package/dist/chunk-Z52RA3NC.js.map +0 -1
  125. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  126. package/dist/inspect-LMKOXE4Y.js +0 -96
  127. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  128. package/dist/install-LEX3ENQ6.js +0 -387
  129. package/dist/install-LEX3ENQ6.js.map +0 -1
  130. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  131. package/dist/outcome-N7TAK6WR.js +0 -66
  132. package/dist/outcome-N7TAK6WR.js.map +0 -1
  133. package/dist/publish-BKBQQAW4.js.map +0 -1
  134. package/dist/usdc-JIAJW4SV.js +0 -22
  135. package/dist/wallet-CWEMYVIH.js +0 -179
  136. package/dist/wallet-CWEMYVIH.js.map +0 -1
  137. package/dist/wallet-PA54CRBL.js +0 -30
  138. /package/dist/{_esm-FEASBWRP.js.map → _esm-N4KAVXQR.js.map} +0 -0
  139. /package/dist/{ccip-NQXCEK2U.js.map → buy-YMXXVNFH.js.map} +0 -0
  140. /package/dist/{ccip-XR5NE5QK.js.map → candidate-H7FR4AU5.js.map} +0 -0
  141. /package/dist/{config-VELDKLHY.js.map → ccip-RPPPKTJR.js.map} +0 -0
  142. /package/dist/{doctor-T3KWNNP2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  143. /package/dist/{chunk-S3IGX57D.js.map → chunk-FU6MCSLG.js.map} +0 -0
  144. /package/dist/{chunk-5CLSD5YN.js.map → chunk-KYQVEKP5.js.map} +0 -0
  145. /package/dist/{chunk-RRN3YTK7.js.map → chunk-KZAAWQNP.js.map} +0 -0
  146. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POJRB2AE.js.map} +0 -0
  147. /package/dist/{chunk-CYOF7ROH.js.map → chunk-S5RYMCV6.js.map} +0 -0
  148. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-U5S527PP.js.map} +0 -0
  149. /package/dist/{chunk-RY4XKNV3.js.map → chunk-UHTVXQ2O.js.map} +0 -0
  150. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-W6R3HAAG.js.map} +0 -0
  151. /package/dist/{chunk-HIVZG55D.js.map → chunk-XJN5WUKL.js.map} +0 -0
  152. /package/dist/{chunk-HSDCI7OV.js.map → chunk-YLYINX2H.js.map} +0 -0
  153. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → config-VCOS7P5K.js.map} +0 -0
  154. /package/dist/{secp256k1-N3ZHU7LB.js.map → doctor-WS65JG3V.js.map} +0 -0
  155. /package/dist/{usdc-JIAJW4SV.js.map → ethersCompat-Df4a6QIZ-WHYKB6HA.js.map} +0 -0
  156. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → inspect-SFJWUQHO.js.map} +0 -0
  157. /package/dist/{wallet-PA54CRBL.js.map → outcome-GNYCSZ7J.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/doctor.ts","../src/lib/permissions.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { homedir } from 'node:os';\nimport { CliError } from '../lib/errors';\nimport {\n CLI_SKILL_NAMES,\n HOSTED_SKILL_NAME,\n anyTenjinSkill,\n cliSkillsWired,\n detectHarnesses,\n harnessFlagFor,\n harnessInPlay,\n harnessReads,\n harnessRequested,\n missingCliSkills,\n onPath,\n readAllWiring,\n shadowedCliSkills,\n} from '../lib/skill-wiring';\nimport type {\n DirState,\n HarnessTarget,\n HarnessWiring,\n NotInvocableReason,\n} from '../lib/skill-wiring';\nimport { fetchJson } from '../lib/http';\nimport { CLIENT_HEADER } from '../lib/client-meta';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { trimSlash } from '../lib/url';\nimport { configPath } from '../lib/paths';\nimport { toMoney } from '../lib/money';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { recommendedPermissions, renderPermissionsBlock } from '../lib/permissions';\nimport type { PartialConfig } from '../lib/config';\nimport type { ErrorCode } from '../schemas';\nimport type { Io } from '../lib/output';\nimport type { WalletDescription, WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * One environment/reachability check. The doctor agent builds the check list\n * against this shape without changing it: `required` drives the exit code (exit\n * 0 iff every required check is ok), `status` drives the TTY rendering, and a\n * `fix` is mandatory on every failure (spec 10). Warn-level checks never fail\n * the command.\n */\nexport interface CheckResult {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n /**\n * Optional structured payload for machine consumers, so `--json` carries the\n * check's findings as data instead of only as the prose in `detail`. Additive\n * and per-check; the human renderer ignores it.\n */\n data?: unknown;\n}\n\n/** ~$20 in atomic USDC (6 decimals). Above this, the pocket-money wallet warns. */\nconst POCKET_MONEY_CEILING_ATOMIC = 20_000_000n;\n\n/**\n * `doctor` is an allowlisted verb an unattended agent runs on its own, and its\n * `fix:` lines reach that agent both on the TTY and in `error.details.checks`.\n * So they name the CONFIGURED base URL and the operator command that changes it,\n * never `--base-url`: the flag rides every allowlisted verb (see FLAG_CAVEAT in\n * lib/permissions), and a fix line telling the agent to pass it would be the CLI\n * coaching the exact move the skills forbid. `config set` is not allowlisted, so\n * pointing there routes the change through the operator by construction.\n */\nconst FIX_POINT_AT_TENJIN_API =\n 'Point the configured base URL at a Tenjin API (expected an OpenAPI document): `tenjin config set baseUrl <url>`.';\nconst FIX_CHECK_NETWORK_AND_BASE_URL =\n 'Check your network connection and the configured base URL (`tenjin config get baseUrl`).';\n\n/**\n * A CheckResult plus the error code to raise if it is a *required* failure. Only\n * required checks carry a `failCode`; the outcome step raises the first one, so\n * the failure envelope's `error.code` names what actually broke (api-contract\n * unreachable vs malformed differ) while still carrying the whole check list.\n */\ninterface BuiltCheck {\n result: CheckResult;\n failCode?: ErrorCode;\n}\n\nexport interface DoctorDeps {\n /** Environment for wallet-key detection and settings precedence. */\n env?: NodeJS.ProcessEnv;\n /** Injected fetch for the reachability checks; tests pass a canned stub. */\n fetchImpl?: typeof fetch;\n /** Inject the active wallet provider. When set, NO local fs/env is consulted —\n * the provider owns its own describe() and diagnostics(), so a remote provider's\n * checks can't be contaminated by a stale local wallet file. */\n provider?: WalletProvider;\n /** Home directory root for the skill-wiring check. Defaults to os.homedir(); tests\n * (and `install`, which reuses these checks) inject their own. */\n homeDir?: string;\n /** PATH probe for the `claude`/`codex` binaries, half of harness detection. Defaults\n * to probing `env.PATH`, so a test passing `env: {}` detects neither. */\n which?: (bin: string) => boolean;\n}\n\n/**\n * The full check list plus the first required failure, if any. `install` reuses\n * this to run the doctor checks as its last step and EMBED the summary without\n * throwing (D39: doctor is diagnostics, it never blocks the caller); `runDoctor`\n * wraps it and turns a required failure into the thrown failure envelope.\n */\nexport interface DoctorChecks {\n checks: CheckResult[];\n failure?: { code: ErrorCode; result: CheckResult };\n}\n\nexport async function collectDoctorChecks(\n ctx: CommandContext,\n deps: DoctorDeps = {},\n): Promise<DoctorChecks> {\n const env = deps.env ?? process.env;\n const { config, check: configCheck } = await loadConfigForDoctor(ctx.dataDir);\n const settings = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env });\n const baseUrl = settings.baseUrl.value;\n\n const built: BuiltCheck[] = [\n checkNode(),\n configCheck,\n await checkApiContract(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkReadPath(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkSearchContract(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkSkills(\n deps.homeDir ?? homedir(),\n deps.which ?? ((bin) => onPath(bin, env)),\n config.install?.harness ?? [],\n ),\n ];\n\n // The wallet/custody/balance checks all come from the ACTIVE provider: it owns\n // describe() and diagnostics(), so doctor never runs its own fs/env probe.\n for (const result of await checkWallet(ctx, deps, env, settings.rpcUrl.value)) {\n built.push({ result });\n }\n\n const checks = built.map((b) => b.result);\n const firstFail = built.find((b) => b.result.required && b.result.status === 'fail');\n if (firstFail === undefined) return { checks };\n return { checks, failure: { code: firstFail.failCode ?? 'INTERNAL', result: firstFail.result } };\n}\n\nexport async function runDoctor(\n ctx: CommandContext,\n deps: DoctorDeps = {},\n): Promise<CommandResult> {\n const { checks, failure } = await collectDoctorChecks(ctx, deps);\n if (failure !== undefined) {\n const r = failure.result;\n // The allowlist rides on the FAILURE envelope too. An operator whose fresh\n // install is broken is the likeliest one to be reading doctor output at all,\n // and the earlier version dropped the block on exactly that path while the\n // comment below claimed otherwise. The human failure path still renders only\n // the error and its fix (that is emitFailure's contract, not doctor's), so\n // the machine payload is where this has to land.\n throw new CliError(failure.code, r.detail, {\n ...(r.fix !== undefined ? { fix: r.fix } : {}),\n details: { checks, permissions: recommendedPermissions() },\n });\n }\n\n // The discoverability surface for the auto-mode denial problem (#33): an\n // operator whose agent just got denied runs doctor and gets the exact lines to\n // paste, without having to already know they exist. It reports nothing about the\n // local machine, so it is deliberately NOT a check: it can never pass or fail.\n return {\n data: { status: 'pass', checks, permissions: recommendedPermissions() },\n humanLines: [...renderDoctorHuman(ctx.io, checks), '', ...renderPermissionsBlock()],\n };\n}\n\nfunction checkNode(): BuiltCheck {\n const version = process.versions.node;\n const major = Number.parseInt(version.split('.')[0] ?? '0', 10);\n if (major >= 22) {\n return { result: { name: 'node', status: 'ok', required: true, detail: `Node ${version}` } };\n }\n return {\n result: {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `Node ${version} is unsupported (need >= 22)`,\n fix: 'Install Node 22 or newer',\n },\n failCode: 'NODE_UNSUPPORTED',\n };\n}\n\n/**\n * loadRawConfig throws CONFIG_INVALID on a bad file (which we convert into a\n * failing check) but the config value is also needed for baseUrl/rpcUrl\n * resolution; an invalid file falls back to {} so the reachability checks still\n * run and appear in the list, and config is reported as the first required fail.\n */\nasync function loadConfigForDoctor(\n dataDir: string,\n): Promise<{ config: PartialConfig; check: BuiltCheck }> {\n try {\n const config = await loadRawConfig(dataDir);\n const detail =\n Object.keys(config).length === 0\n ? 'No config file; using defaults'\n : `Config at ${configPath(dataDir)} is valid`;\n return { config, check: { result: { name: 'config', status: 'ok', required: true, detail } } };\n } catch (err) {\n if (err instanceof CliError && err.code === 'CONFIG_INVALID') {\n return {\n config: {},\n check: {\n result: {\n name: 'config',\n status: 'fail',\n required: true,\n detail: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n },\n failCode: 'CONFIG_INVALID',\n },\n };\n }\n throw err;\n }\n}\n\nasync function checkApiContract(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n const url = `${trimSlash(baseUrl)}/openapi.json`;\n const res = await fetchJson(url, {\n timeoutMs,\n fetchImpl,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n });\n if (!res.ok) {\n const malformed = res.kind === 'invalid-json';\n return {\n result: {\n name: 'api-contract',\n status: 'fail',\n required: true,\n detail: malformed\n ? `OpenAPI document at ${url} was not valid JSON`\n : `Could not reach the Tenjin API at ${url}: ${res.message}`,\n fix: malformed ? FIX_POINT_AT_TENJIN_API : FIX_CHECK_NETWORK_AND_BASE_URL,\n },\n failCode: malformed ? 'CONTRACT_MISMATCH' : 'API_UNREACHABLE',\n };\n }\n const version = infoVersion(res.json);\n if (version === undefined) {\n return {\n result: {\n name: 'api-contract',\n status: 'fail',\n required: true,\n detail: `OpenAPI document at ${url} is missing a string info.version`,\n fix: FIX_POINT_AT_TENJIN_API,\n },\n failCode: 'CONTRACT_MISMATCH',\n };\n }\n return {\n result: {\n name: 'api-contract',\n status: 'ok',\n required: true,\n detail: `Tenjin API ${version} at ${baseUrl}`,\n },\n };\n}\n\n/**\n * WARN-level (never fails doctor): is the A2 search endpoint advertised in the\n * OpenAPI doc? Absent means the deployment predates A2 (the buy/search path will\n * not work against it yet). Warn-only because doctor's job is a working READ path,\n * and search is additive.\n */\nasync function checkSearchContract(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n const url = `${trimSlash(baseUrl)}/openapi.json`;\n const res = await fetchJson(url, {\n timeoutMs,\n fetchImpl,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n });\n if (!res.ok) {\n return {\n result: {\n name: 'search-contract',\n status: 'warn',\n required: false,\n detail: `Could not confirm the search endpoint at ${url}`,\n fix: 'Check the configured base URL (`tenjin config get baseUrl`); search/buy need the A2 endpoints deployed.',\n },\n };\n }\n const present = hasSearchPath(res.json);\n return {\n result: present\n ? {\n name: 'search-contract',\n status: 'ok',\n required: false,\n detail: 'Search endpoint advertised',\n }\n : {\n name: 'search-contract',\n status: 'warn',\n required: false,\n detail: 'This deployment does not advertise POST /api/agent/search (A2 not deployed)',\n fix: 'search/buy need A2 deployed; point the configured base URL at a deploy that has it (`tenjin config set baseUrl <url>`).',\n },\n };\n}\n\nfunction hasSearchPath(json: unknown): boolean {\n if (!isRecord(json)) return false;\n const paths = json.paths;\n return isRecord(paths) && '/api/agent/search' in paths;\n}\n\n/**\n * WARN-level (never fails doctor): is the harness skill wiring usable? #35 was\n * invisible without a screen recording, because the publish skill was on disk yet\n * the model never saw it and only the hosted skill answered publish asks.\n *\n * Verdicts are per DIRECTORY, never unioned across them — in EITHER direction.\n * Unioning the problems contradicts itself on a real machine: a Claude-only install\n * leaves a stray hosted skill in ~/.agents/skills, and flat-mapping announced both\n * CLI skills \"missing\" in the same sentence that listed them wired. Unioning the\n * successes is the same bug inverted, and worse: Claude Code reads ~/.claude/skills\n * and Codex reads ~/.agents/skills, so a wired .agents cannot answer for .claude,\n * and asking whether SOME directory is wired reported `ok` on a machine where\n * `tenjin-publish` was unreachable from Claude Code — exactly the #35 shape.\n *\n * So each directory is judged alone, and only when a harness on this machine\n * actually reads it (`harnessReads`, the probes `install` picks targets with). That\n * gate is what keeps a leftover mirror quiet: a hosted-only ~/.agents/skills with no\n * Codex is nobody's problem, while a hosted-only ~/.claude/skills with Claude Code\n * installed is the bug.\n *\n * Warn and never required: a CI or server machine legitimately has no harness, so\n * this must not move the exit code.\n */\n/**\n * `requested` is the `--harness` set a past `install` recorded (config `install.harness`).\n * It joins detection in deciding which directories are in play, and rides in the data as\n * its own field so `harnessPresent` keeps meaning \"a harness detected here reads this\".\n */\nasync function checkSkills(\n home: string,\n which: (bin: string) => boolean,\n requested: readonly HarnessTarget[],\n): Promise<BuiltCheck> {\n const present = detectHarnesses(home, which);\n const wiring = await readAllWiring(home);\n const data = {\n directories: wiring.map((w) => ({\n ...w,\n harnessPresent: harnessReads(home, w.dir, present),\n requested: harnessRequested(home, w.dir, requested),\n })),\n };\n const inPlay = wiring.filter((w) => anyTenjinSkill(w));\n\n if (inPlay.length === 0) {\n // Same fixFor path every other branch uses, over the same harnessInPlay\n // predicate (detected OR requested) — filtering on `requested` alone named\n // only the recorded directory and left a DETECTED one unwired, which just\n // swapped which directory the first command missed. Gated on\n // `requested.length > 0` so a machine with no record at all keeps the plain\n // `tenjin install` rather than newly spelling out a detected harness that\n // nobody asked to see named.\n const targeted =\n requested.length > 0\n ? wiring.filter((w) => harnessInPlay(home, w.dir, present, requested))\n : [];\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `No Tenjin skills wired under ${home} (looked in .claude/skills and .agents/skills)`,\n fix: targeted.length > 0 ? fixFor(home, targeted) : 'tenjin install',\n data,\n },\n };\n }\n\n // Every directory in play must carry BOTH CLI skills, model-invocable. Anything less\n // is the defect, whether it is shadowed, half-installed, hosted-only or absent; a\n // directory neither detected nor asked for is described but never warned about.\n const broken = wiring.filter(\n (w) => harnessInPlay(home, w.dir, present, requested) && !cliSkillsWired(w),\n );\n if (broken.length > 0) {\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `${broken.map(describeProblem).join('; ')}. Full state: ${describeWiring(inPlay)}`,\n fix: fixFor(home, broken),\n data,\n },\n };\n }\n\n return {\n result: {\n name: 'skills',\n status: 'ok',\n required: false,\n detail: `${CLI_SKILL_NAMES.join(' + ')} wired: ${describeWiring(inPlay)}`,\n data,\n },\n };\n}\n\n/** What is wrong in ONE directory, naming the directory and the skills. */\nfunction describeProblem(w: HarnessWiring): string {\n const shadowed = shadowedCliSkills(w);\n const missing = missingCliSkills(w);\n const parts: string[] = [];\n // Grouped BY REASON, not into one clause: the two claims differ in strength. A\n // readable file with the flag set is a fact; an unreadable one is a disjunction,\n // because the whole reason we cannot assert the flag is that we could not read it.\n // Merging them would spread that hedge onto a skill we know the answer for.\n const unreadable = shadowed.filter((n) => reasonFor(w, n) === 'unreadable');\n const disabled = shadowed.filter((n) => reasonFor(w, n) !== 'unreadable');\n if (disabled.length > 0) {\n parts.push(\n `${disabled.join(', ')} installed but not model-invocable (disable-model-invocation: true)`,\n );\n }\n if (unreadable.length > 0) {\n parts.push(\n `${unreadable.join(', ')} installed but not model-invocable (unreadable or disable-model-invocation: true)`,\n );\n }\n // Naming both by name reads as a half-install; when NEITHER is there the state is\n // \"this harness has no CLI skills at all\", which is a different sentence.\n if (missing.length === CLI_SKILL_NAMES.length) {\n parts.push(\n w.state === 'hosted-only'\n ? `the hosted ${HOSTED_SKILL_NAME} skill is here but neither CLI skill is wired`\n : 'neither CLI skill is wired',\n );\n } else if (missing.length > 0) parts.push(`${missing.join(', ')} missing`);\n return `${w.dir}: ${parts.join(' and ')}`;\n}\n\nfunction reasonFor(w: HarnessWiring, name: string): NotInvocableReason | undefined {\n return w.skills.find((s) => s.name === name)?.reason;\n}\n\n/** Is the hosted zero-install mirror in THIS directory? */\nfunction hostedHere(w: HarnessWiring): boolean {\n return w.skills.find((s) => s.name === HOSTED_SKILL_NAME)?.present === true;\n}\n\n/**\n * A fix that can actually clear the warning. A bare `tenjin install` only targets\n * the directories detection picks, so a problem in ~/.agents/skills on a\n * Claude-only machine needs `--harness shared` spelled out.\n */\nfunction fixFor(home: string, dirs: HarnessWiring[]): string {\n const flags = [...new Set(dirs.map((w) => harnessFlagFor(home, w.dir)))];\n return `tenjin install ${flags.map((f) => `--harness ${f}`).join(' ')}`;\n}\n\n/** One-line per-directory summary: `<dir> -> <skills> (<posture>)`. */\nfunction describeWiring(wiring: HarnessWiring[]): string {\n return wiring\n .map((w) => {\n const parts = w.skills\n .filter((s) => s.present)\n .map((s) =>\n s.modelInvocable === false ? `${s.name} [${s.reason ?? 'shadowed'}]` : s.name,\n );\n return `${w.dir} -> ${parts.join(', ')} (${posture(w)})`;\n })\n .join('; ');\n}\n\n/**\n * The precedence half of the `wired` posture is only true when there is a mirror\n * here to take precedence OVER. `classify` keys `wired` off the two CLI skills\n * alone, so a directory whose mirror was deleted is `wired` with no `tenjin` in it,\n * and the unconditional string claimed a file the same line had just not listed.\n */\nfunction posture(w: HarnessWiring): string {\n if (w.state !== 'wired') return POSTURE[w.state];\n return hostedHere(w)\n ? 'CLI skills wired, take precedence over the hosted mirror'\n : 'CLI skills wired';\n}\n\nconst POSTURE: Record<DirState, string> = {\n empty: 'no Tenjin skills',\n 'hosted-only': 'hosted skill only, no CLI skills here',\n partial: 'only one CLI skill',\n // \"at least one\": a directory with one CLI skill shadowed and the other absent\n // classifies as `shadowed` too, and \"CLI skills present\" would be false there.\n shadowed: 'at least one CLI skill present but not model-invocable',\n wired: 'CLI skills wired, take precedence over the hosted mirror',\n};\n\nasync function checkReadPath(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n // The shipped public read path. The A2 search-contract check is a B2 follow-up.\n // Probe the UNFILTERED listing: the server logs every nonblank first-page `q`\n // as agent search demand, so a `q` here would fabricate that demand into the\n // experiment this CLI exists to measure. Never add a `q` to this probe.\n const url = `${trimSlash(baseUrl)}/api/articles?limit=1`;\n const res = await fetchJson(url, {\n timeoutMs,\n fetchImpl,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n });\n if (!res.ok) {\n return {\n result: {\n name: 'read-path',\n status: 'fail',\n required: true,\n detail: `Read path ${url} failed: ${res.message}`,\n fix: FIX_CHECK_NETWORK_AND_BASE_URL,\n },\n failCode: 'API_UNREACHABLE',\n };\n }\n const items = isRecord(res.json) ? res.json.items : undefined;\n if (!Array.isArray(items)) {\n return {\n result: {\n name: 'read-path',\n status: 'fail',\n required: true,\n detail: `Read path ${url} did not return an items array`,\n fix: 'Point the configured base URL at a Tenjin API: `tenjin config set baseUrl <url>`.',\n },\n failCode: 'API_UNREACHABLE',\n };\n }\n return {\n result: { name: 'read-path', status: 'ok', required: true, detail: `Read path OK at ${url}` },\n };\n}\n\n/**\n * Diagnose the wallet the CLI would actually use, entirely through the ACTIVE\n * provider. An injected provider owns everything — no local file or env is touched.\n * With no injected provider we do ONE cheap fs/env probe purely to decide whether\n * any credential exists: none → emit the \"no wallet\" warn WITHOUT importing the\n * wallet lib (that import statically pulls viem, and a no-wallet run must not parse\n * it). Otherwise the provider describes itself (address + source), reports its own\n * custody warnings, and the balance probes describe()'s address. A custody problem\n * (bad key, provider refusal) is warn-level, never a hard fail.\n */\nasync function checkWallet(\n ctx: CommandContext,\n deps: DoctorDeps,\n env: NodeJS.ProcessEnv,\n rpcUrl: string,\n): Promise<CheckResult[]> {\n const provider = deps.provider ?? (await resolveLocalProviderOrNull(ctx, env));\n if (provider === null) return [noWalletCheck()];\n\n const { describeWallet } = await import('../lib/wallet');\n let desc: WalletDescription;\n try {\n desc = await describeWallet(provider);\n } catch (err) {\n if (err instanceof CliError && err.code === 'WALLET_MISSING') return [noWalletCheck()];\n return [walletWarn(err)];\n }\n\n const checks: CheckResult[] = [\n {\n name: 'wallet',\n status: 'ok',\n required: false,\n detail: `Wallet ${desc.address} (${desc.credentialSource})`,\n },\n ];\n // Custody warnings are the provider's own (perms, env-shadow for the local\n // provider; none for a remote one). Render each as a warn check; the fix text,\n // when there is one, is carried inline in the warning string.\n for (const warning of (await provider.diagnostics()).warnings) {\n checks.push({ name: 'wallet-custody', status: 'warn', required: false, detail: warning });\n }\n checks.push(await checkBalance(desc.address, rpcUrl));\n return checks;\n}\n\n/**\n * The active local provider, or null when no credential exists at all. The null\n * path never imports the wallet lib, keeping a no-wallet doctor run off viem.\n */\nasync function resolveLocalProviderOrNull(\n ctx: CommandContext,\n env: NodeJS.ProcessEnv,\n): Promise<WalletProvider | null> {\n const envKey = env.TENJIN_WALLET_KEY;\n const envKeySet = typeof envKey === 'string' && envKey.length > 0;\n if (!envKeySet && !(await walletFileExists(ctx.dataDir))) return null;\n const { resolveWalletProvider } = await import('../lib/wallet');\n return resolveWalletProvider(ctx);\n}\n\nfunction noWalletCheck(): CheckResult {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: 'No wallet; needed only for buy/publish',\n fix: 'tenjin wallet create',\n };\n}\n\nfunction walletWarn(err: unknown): CheckResult {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: err instanceof Error ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n };\n}\n\n/**\n * Balance is best-effort: a zero balance is a fundable warning and an RPC flake\n * must never fail doctor. viem loads only here, via a lazy import, so a doctor\n * run without a wallet never parses the viem chunk.\n */\nasync function checkBalance(address: string, rpcUrl: string): Promise<CheckResult> {\n try {\n const { getUsdcBalance } = await import('../lib/usdc');\n const balance = await getUsdcBalance(address as `0x${string}`, rpcUrl);\n if (balance === 0n) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: 'Wallet USDC balance is 0',\n fix: 'Send USDC on Base. $5 covers ~50 typical resources.',\n };\n }\n const money = toMoney(balance.toString());\n // Pocket-money posture (roadmap B2): a plaintext-adjacent local key should\n // hold only small change, so a balance over ~$20 is a warn, not an error.\n if (balance > POCKET_MONEY_CEILING_ATOMIC) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: `Balance ${money.usd} USDC is above the ~$20 pocket-money ceiling`,\n fix: 'Keep only small change in the CLI wallet; sweep the excess to cold storage.',\n };\n }\n return {\n name: 'balance',\n status: 'ok',\n required: false,\n detail: `Balance ${money.usd} USDC (${money.atomic} atomic)`,\n };\n } catch (err) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: `Could not read balance: ${err instanceof Error ? err.message : String(err)}`,\n fix: 'Check rpcUrl or retry; a balance read failure never fails doctor.',\n };\n }\n}\n\nexport function renderDoctorHuman(io: Io, checks: CheckResult[]): string[] {\n const nameWidth = Math.max(...checks.map((c) => c.name.length));\n const lines: string[] = [];\n for (const c of checks) {\n const icon =\n c.status === 'ok'\n ? paint(io, 'green', '✓')\n : c.status === 'warn'\n ? paint(io, 'yellow', '!')\n : paint(io, 'red', '✗');\n // `detail` and `fix` interpolate SERVER-sourced strings (the OpenAPI\n // info.version, a provider's error text). doctor now prints them directly\n // above the allowlist block the operator is told to paste, so a newline or\n // ANSI in a hostile deployment's version string could forge a second, wider\n // \"allowlist\" section in the terminal. Sanitize at the render seam: output.ts\n // exempts doctor on the assumption it only paints its OWN text, which stopped\n // being true the moment these lines sat next to a copy-paste block.\n lines.push(\n `${icon} ${c.name.padEnd(nameWidth)} ${paint(io, 'dim', sanitizeForTerminal(c.detail))}`,\n );\n if (c.status !== 'ok' && c.fix !== undefined) {\n lines.push(` ${paint(io, 'dim', `fix: ${sanitizeForTerminal(c.fix)}`)}`);\n }\n }\n return lines;\n}\n\n/**\n * Color for stderr, honoring NO_COLOR and the target's color depth: styleText\n * takes the stderr stream when it is a genuine Stream (it throws on anything\n * else, so a test/redirected sink falls back to the default plain check).\n */\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });\n return styleText(format, text);\n}\n\nfunction infoVersion(json: unknown): string | undefined {\n if (!isRecord(json)) return undefined;\n const info = json.info;\n if (!isRecord(info)) return undefined;\n return typeof info.version === 'string' ? info.version : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n","/**\n * The recommended HARNESS permission allowlist: the exact rule lines an operator\n * pastes into Claude Code (or an equivalent harness) so auto mode stops denying\n * the free Tenjin verbs, and so the one paying verb is cleared deliberately\n * rather than by accident.\n *\n * This is a HARNESS-side allowlist (which shell commands the agent may run at\n * all). It is NOT the CLI's spend policy and shares nothing with it: the shipped\n * `allowlistCreators` config key gates WHO you may pay, this file gates WHICH\n * COMMANDS the harness will run without a prompt. The two are deliberately kept\n * apart in name and in code — clearing `Bash(tenjin buy:*)` here never raises a\n * spend cap. That is a claim about this file, NOT a claim that the spend policy\n * stops an allowlisted `buy`: `--yes` is an ordinary flag on an allowlisted verb\n * and `confirmSpend` returns true on it before any TTY check\n * (src/commands/buy.ts), so under CONFIG_DEFAULTS nothing denies. See\n * OPT_IN_ALLOWLIST's note for the walk-through.\n *\n * These are static, shipped constants on purpose: there is NO config key for\n * them. An operator-editable \"which commands may run\" list stored next to the\n * spend policy would be a second, weaker copy of a control the harness already\n * owns, and a CLI that could widen its own permission grant is exactly the shape\n * this file exists to avoid.\n *\n * Scope: `tenjin mcp` exposes the same command cores over MCP, where the harness\n * gates TOOLS, not Bash lines. These rules say nothing about that surface, which\n * is why `tenjin mcp` is itself never recommended here: clearing it would route\n * around every rule below. MCP_CAVEAT names the tools to leave gated for an\n * operator who runs the server anyway.\n *\n * LIMIT OF A PREFIX RULE, read this before adding an entry: the rule constrains\n * the VERB and nothing else. `addGlobalFlags` (src/cli.ts) puts `--json`,\n * `--timeout`, and `--base-url` on every leaf command, so every rule below also\n * clears `--base-url <url>` in trailing position. `--base-url` is validated as a\n * URL and nothing more, and it wins settings precedence, so it re-points the\n * trust boundary itself: the `search` question goes to that host, `doctor` probes\n * it, and `assertOnBaseOrigin` only checks that a resource URL shares an origin\n * with the CONFIGURED base, so an attacker-controlled pair satisfies the pin. No\n * prefix syntax expresses \"this verb but not that flag\", so the mitigation is\n * disclosure rather than a narrower rule: FLAG_CAVEAT prints alongside the rules\n * on every surface, and the skills tell the agent never to pass `--base-url` on\n * an allowlisted verb. Pinning the paying path to a constant origin instead is\n * the real fix and is an x402/payments-semantics change, tracked separately.\n */\n\n/** One pasteable allowlist rule plus why it is safe (or what it costs). */\nexport interface AllowlistEntry {\n /** The exact line to add to the harness permission allowlist. */\n rule: string;\n /** The verb it clears. */\n command: string;\n /** Why it is safe to pre-clear, or what the operator is opting into. */\n note: string;\n}\n\n/** A verb deliberately kept OUT of the recommended allowlist, and why. */\nexport interface ExcludedVerb {\n command: string;\n reason: string;\n}\n\n/**\n * FREE verbs: no wallet, no signing, no payment. Not all of them are read-only,\n * and the difference is disclosed rather than papered over — `search` POSTs the\n * (generalized, anonymous) question off-machine and records it locally, and\n * `outcome` POSTs a report that moves the marketplace's reuse signal. Both are\n * unauthenticated remote writes. Pre-clearing them is defensible because they\n * cost nothing and carry no credential; calling them read-only to justify it\n * would not be.\n *\n * Rules are PREFIX rules: `Bash(tenjin search:*)` clears commands that start with\n * `tenjin search` and nothing else. The narrow `wallet show` / `wallet balance` /\n * `config get` / `candidate list` forms are deliberate: a `Bash(tenjin wallet:*)`\n * or `Bash(tenjin config:*)` rule would silently swallow `wallet create` and\n * `config set`, and `config set` can raise the spend caps.\n *\n * Two known gaps, both fail-closed (denied, never wrongly allowed):\n * - Bare `tenjin config` (runConfigList) is as read-only as `config get`, but no\n * prefix rule reaches it without also covering `config set`, so it stays out.\n * Use `tenjin config get <key>`, which is a different supported command rather\n * than a reworded one.\n * - Group-level flag forms like `tenjin wallet --json show` are not covered.\n * Put global flags AFTER the leaf verb (`tenjin wallet show --json`); the\n * CLI parses either, and only the trailing form matches these rules.\n */\nexport const ALWAYS_SAFE_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin search:*)',\n command: 'tenjin search',\n note:\n 'Free anonymous marketplace search. No wallet, no signing, no payment. ' +\n 'Not read-only: it POSTs the generalized question off-machine and records ' +\n 'the search locally.',\n },\n {\n rule: 'Bash(tenjin inspect:*)',\n command: 'tenjin inspect',\n note: 'Free pre-purchase card and preview. Never signs, never pays, never saves.',\n },\n {\n rule: 'Bash(tenjin outcome:*)',\n command: 'tenjin outcome',\n note:\n 'Free honest outcome report on a past search. No wallet, no payment. ' +\n 'Not read-only: it POSTs a report that moves the marketplace reuse signal.',\n },\n {\n rule: 'Bash(tenjin doctor:*)',\n command: 'tenjin doctor',\n note: 'Read-only local environment and API reachability diagnostics.',\n },\n {\n rule: 'Bash(tenjin wallet show:*)',\n command: 'tenjin wallet show',\n note: 'Prints the wallet address and key source. Never prints the key.',\n },\n {\n rule: 'Bash(tenjin wallet balance:*)',\n command: 'tenjin wallet balance',\n note: 'Read-only USDC balance query on Base.',\n },\n {\n rule: 'Bash(tenjin config get:*)',\n command: 'tenjin config get',\n note:\n 'Reads one effective config value. `config set` is excluded on purpose. ' +\n 'Note `config get rpcUrl` returns your RPC URL, which commonly embeds a ' +\n 'provider API key: no wallet secret, but a credential-adjacent read.',\n },\n {\n rule: 'Bash(tenjin candidate list:*)',\n command: 'tenjin candidate list',\n note: 'Lists local parked drafts. Candidates are local files; nothing uploads.',\n },\n];\n\n/**\n * The one paying verb, offered as an EXPLICIT opt-in line rather than shipped in\n * the safe set.\n *\n * Read the note carefully before pasting the line: on the DEFAULT config this\n * rule authorizes unattended spending up to the wallet balance. Walking\n * evaluateSpendPolicy (lib/policy.ts) against CONFIG_DEFAULTS with an agent that\n * passes `--yes` (which this repo's own skill snippet offers):\n * - `maxPriceAtomic` is unset unless the agent chooses to pass `--max-price`;\n * - `allowlistCreators` is empty, so the creator gate is off;\n * - `sessionBudget` is '0', which `if (policy.sessionBudgetAtomic > 0n)` reads\n * as DISABLED, not as a zero ceiling;\n * - `maxAutoSpend` '0' and `confirm` 'always' both land on `confirm`, and\n * `confirmSpend` returns true on `--yes` before any TTY check.\n * Nothing denies. Note the asymmetry that makes the pair read safer than it is:\n * `maxAutoSpend: '0'` means \"auto-approve nothing\" while `sessionBudget: '0'`\n * means \"no ceiling at all\".\n */\nexport const OPT_IN_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin buy:*)',\n command: 'tenjin buy',\n note:\n 'SPENDS USDC on Base, unrefundably. This authorizes UNATTENDED purchases: ' +\n '`--yes` is an ordinary flag on the same allowlisted verb and it clears the ' +\n 'confirm gate, so on the default config nothing stops a spend up to your ' +\n 'wallet balance. Set a real ceiling first with ' +\n '`tenjin config set maxAutoSpend <usd>` and ' +\n '`tenjin config set sessionBudget <usd>` (sessionBudget 0 means NO ceiling, ' +\n 'not a zero one). This line never raises a spend cap by itself, but do not ' +\n 'read that as a human being on every purchase. Fund small.',\n },\n];\n\n/**\n * Verbs that must NEVER appear in the recommended allowlist, with the reason each\n * one is a human decision. `tenjin send` is the wallet escape hatch (tenjin-agent\n * #40) and heads this list: it moves USDC to an arbitrary address, outside the\n * spend policy that bounds `buy`. Naming it here is load-bearing even in versions\n * where the verb does not exist yet — the exclusion ships before the verb does.\n */\nexport const NEVER_ALLOWLISTED: readonly ExcludedVerb[] = [\n {\n command: 'tenjin send',\n reason:\n 'Moves USDC out of the wallet to an arbitrary address (the escape hatch, #40). ' +\n 'Irreversible and not bounded by the buy spend policy. Always a human decision.',\n },\n {\n command: 'tenjin publish',\n reason: 'Puts your content on a public marketplace under your identity.',\n },\n {\n command: 'tenjin wallet create',\n reason: 'Creates the payment credential; a stray run is a wallet you did not mean to have.',\n },\n {\n command: 'tenjin config set',\n reason:\n 'Can raise maxAutoSpend / sessionBudget / confirm, i.e. widen the agent’s own spend policy.',\n },\n {\n command: 'tenjin candidate add / tenjin candidate drop',\n reason: 'Writes or discards local drafts; `candidate list` is the read-only half.',\n },\n {\n command: 'tenjin install',\n reason: 'Writes into harness config and skills directories.',\n },\n {\n command: 'tenjin mcp',\n reason:\n 'Long-running server that re-exposes every command core over stdio; ' +\n 'clearing it would indirectly clear everything above.',\n },\n];\n\n/**\n * The flag-surface caveat. A prefix rule pins the verb, never the flags, and the\n * flag that matters is `--base-url`: it is accepted on every leaf, validated only\n * as a URL, and it wins settings precedence, so it moves the destination of every\n * allowlisted verb. Printed with the rules everywhere they are printed, because\n * an operator who only reads the verb list would never learn it.\n */\nexport const FLAG_CAVEAT: readonly string[] = [\n 'Caveat: a prefix rule pins the VERB, not the flags. Every line above also clears',\n '`--base-url <url>` on that verb, which re-points where the question, the probe, and',\n '(for buy) the signature and payment go. Allowlist these verbs only if you are content',\n 'for the agent to choose the destination host, and set the base URL in config instead of',\n 'letting it be an argument. The skills tell agents never to pass --base-url on an',\n 'allowlisted verb, but that is a convention, not an enforced boundary.',\n];\n\n/**\n * The MCP caveat. `tenjin mcp` is never recommended as a Bash rule, but an\n * operator who registers the server anyway is on a different permission surface\n * (tools, not command strings) where three excluded verbs come back.\n */\nexport const MCP_CAVEAT: readonly string[] = [\n 'Running the local MCP server (`tenjin mcp`) instead? That is a different permission',\n 'surface: the harness gates TOOLS there, and these Bash rules do not apply. Leave',\n '`mcp__tenjin__tenjin_publish` and `mcp__tenjin__tenjin_wallet` gated, and treat',\n '`mcp__tenjin__tenjin_candidate` as gated for its add/drop actions. `tenjin_buy` is the',\n 'same opt-in decision as the buy line above.',\n];\n\n/** The machine shape emitted by `tenjin doctor --json` and `tenjin install --json`. */\nexport interface RecommendedPermissions {\n alwaysSafe: AllowlistEntry[];\n optIn: AllowlistEntry[];\n neverAllowlisted: ExcludedVerb[];\n /** Caveats that qualify the rules above; never omit them when rendering. */\n caveats: { flags: string[]; mcp: string[] };\n}\n\nexport function recommendedPermissions(): RecommendedPermissions {\n return {\n alwaysSafe: ALWAYS_SAFE_ALLOWLIST.map((e) => ({ ...e })),\n optIn: OPT_IN_ALLOWLIST.map((e) => ({ ...e })),\n neverAllowlisted: NEVER_ALLOWLISTED.map((e) => ({ ...e })),\n caveats: { flags: [...FLAG_CAVEAT], mcp: [...MCP_CAVEAT] },\n };\n}\n\n/** Every rule this module recommends adding (safe + opt-in). */\nexport function recommendedRules(): string[] {\n return [...ALWAYS_SAFE_ALLOWLIST, ...OPT_IN_ALLOWLIST].map((e) => e.rule);\n}\n\n/**\n * The human block both `doctor` and `install` print. Plain lines; the caller\n * decides how (or whether) to paint them.\n */\nexport function renderPermissionsBlock(): string[] {\n const lines: string[] = [\n 'Auto-mode permission allowlist (add these once, then agents stop being denied):',\n ];\n for (const e of ALWAYS_SAFE_ALLOWLIST) lines.push(` ${e.rule}`);\n lines.push(' Free: no wallet, no signing, no payment. Not all read-only, though:');\n lines.push(' `search` and `outcome` POST to the marketplace (a question, a report).');\n lines.push('');\n lines.push(...FLAG_CAVEAT.map((l) => ` ${l}`));\n lines.push('');\n lines.push('Opt in separately, only if you want unattended purchases:');\n for (const e of OPT_IN_ALLOWLIST) {\n lines.push(` ${e.rule}`);\n lines.push(` ${e.note}`);\n }\n lines.push('');\n lines.push('Never recommended (each one is a human decision):');\n for (const e of NEVER_ALLOWLISTED) lines.push(` ${e.command} - ${e.reason}`);\n lines.push('');\n lines.push(...MCP_CAVEAT.map((l) => ` ${l}`));\n lines.push('');\n lines.push(\n 'Claude Code: add the lines to the \"permissions.allow\" array in .claude/settings.json.',\n );\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;AACvB,SAAS,eAAe;;;ACkFjB,IAAM,wBAAmD;AAAA,EAC9D;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAGJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM;AAAA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AAS,MAAM,IAAQ,QAAyC,MAAsB;AACpF,MAAI,GAAG,kBAAkB,OAAQ,QAAO,UAAU,QAAQ,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC;AACrF,SAAO,UAAU,QAAQ,IAAI;AAC/B;AAEA,SAAS,YAAY,MAAmC;AACtD,MAAI,CAAC,SAAS,IAAI,EAAG,QAAO;AAC5B,QAAM,OAAO,KAAK;AAClB,MAAI,CAAC,SAAS,IAAI,EAAG,QAAO;AAC5B,SAAO,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;AAC3D;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  p,
6
6
  r,
7
7
  t
8
- } from "./chunk-HSDCI7OV.js";
8
+ } from "./chunk-YLYINX2H.js";
9
9
 
10
10
  // node_modules/.pnpm/@signinwithethereum+siwe@4.2.0_viem@2.55.2_typescript@6.0.3_zod@4.4.3_/node_modules/@signinwithethereum/siwe/dist/viemAdapter-By13KInL.js
11
11
  var a2 = /* @__PURE__ */ t({ createViemConfig: () => s });
@@ -28,7 +28,7 @@ var o = [{
28
28
  async function s(e) {
29
29
  let a3;
30
30
  try {
31
- a3 = await import("./_esm-FEASBWRP.js");
31
+ a3 = await import("./_esm-N4KAVXQR.js");
32
32
  } catch {
33
33
  throw new r(i.MISSING_PROVIDER_LIBRARY, "viem installed (npm install viem)", "viem not found");
34
34
  }
@@ -67,4 +67,4 @@ export {
67
67
  a2 as a,
68
68
  s
69
69
  };
70
- //# sourceMappingURL=chunk-CYOF7ROH.js.map
70
+ //# sourceMappingURL=chunk-S5RYMCV6.js.map
@@ -0,0 +1,59 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ latestSearch
4
+ } from "./chunk-CVX6JNGD.js";
5
+ import {
6
+ buildOutcomeItem,
7
+ postOutcomes
8
+ } from "./chunk-3IRDP7TN.js";
9
+ import {
10
+ resolveContextSettings
11
+ } from "./chunk-MDDGEGSW.js";
12
+ import {
13
+ CliError
14
+ } from "./chunk-PAUXMRSF.js";
15
+
16
+ // src/commands/outcome.ts
17
+ async function runOutcome(args, ctx, deps = {}) {
18
+ const searchId = await resolveSearchId(args, ctx);
19
+ const item = buildOutcomeItem({
20
+ status: args.status,
21
+ ...args.resource !== void 0 ? { resourceId: args.resource } : {},
22
+ ...args.contentHash !== void 0 ? { contentHash: args.contentHash } : {}
23
+ });
24
+ const settings = await resolveContextSettings(ctx);
25
+ const result = await postOutcomes(searchId, [item], {
26
+ baseUrl: settings.baseUrl,
27
+ timeoutMs: ctx.flags.timeout,
28
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
29
+ });
30
+ return {
31
+ data: { searchId, status: item.status, accepted: result.accepted },
32
+ humanLines: [`Reported ${item.status} for search ${searchId} (accepted ${result.accepted}).`]
33
+ };
34
+ }
35
+ async function resolveSearchId(args, ctx) {
36
+ if (args.searchId !== void 0 && args.last === true) {
37
+ throw new CliError("USAGE", "Pass either --search-id or --last, not both.", {
38
+ fix: "Use --search-id <id> for a specific search, or --last for the most recent."
39
+ });
40
+ }
41
+ if (args.searchId !== void 0) return args.searchId;
42
+ if (args.last === true) {
43
+ const latest = await latestSearch(ctx.dataDir);
44
+ if (latest === null) {
45
+ throw new CliError("SEARCH_NOT_FOUND", "No local search to target with --last.", {
46
+ fix: "Run `tenjin search` first, or pass --search-id <id>."
47
+ });
48
+ }
49
+ return latest.searchId;
50
+ }
51
+ throw new CliError("USAGE", "An outcome needs a search to report against.", {
52
+ fix: "Pass --search-id <id> or --last."
53
+ });
54
+ }
55
+
56
+ export {
57
+ runOutcome
58
+ };
59
+ //# sourceMappingURL=chunk-TXPPMK4L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/outcome.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildOutcomeItem, postOutcomes } from '../lib/agent-api';\nimport { latestSearch } from '../lib/search-store';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin outcome --search-id <id> --status <s>`, POST to\n * /api/agent/searches/:id/outcomes, closing the reuse loop (used / partially_used\n * / rejected / regenerated / purchase_declined). The searchId is the capability,\n * so no wallet is needed; `--last` sugar targets the most recent local search.\n */\n\nexport interface OutcomeArgs {\n searchId?: string;\n last?: boolean;\n status: string;\n resource?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runOutcome(\n args: OutcomeArgs,\n ctx: CommandContext,\n deps: OutcomeDeps = {},\n): Promise<CommandResult> {\n const searchId = await resolveSearchId(args, ctx);\n const item = buildOutcomeItem({\n status: args.status,\n ...(args.resource !== undefined ? { resourceId: args.resource } : {}),\n ...(args.contentHash !== undefined ? { contentHash: args.contentHash } : {}),\n });\n\n const settings = await resolveContextSettings(ctx);\n const result = await postOutcomes(searchId, [item], {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n return {\n data: { searchId, status: item.status, accepted: result.accepted },\n humanLines: [`Reported ${item.status} for search ${searchId} (accepted ${result.accepted}).`],\n };\n}\n\nasync function resolveSearchId(args: OutcomeArgs, ctx: CommandContext): Promise<string> {\n if (args.searchId !== undefined && args.last === true) {\n throw new CliError('USAGE', 'Pass either --search-id or --last, not both.', {\n fix: 'Use --search-id <id> for a specific search, or --last for the most recent.',\n });\n }\n if (args.searchId !== undefined) return args.searchId;\n if (args.last === true) {\n const latest = await latestSearch(ctx.dataDir);\n if (latest === null) {\n throw new CliError('SEARCH_NOT_FOUND', 'No local search to target with --last.', {\n fix: 'Run `tenjin search` first, or pass --search-id <id>.',\n });\n }\n return latest.searchId;\n }\n throw new CliError('USAGE', 'An outcome needs a search to report against.', {\n fix: 'Pass --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gD;AAAA,IAC1E,KAAK;AAAA,EACP,CAAC;AACH;","names":[]}
@@ -60,7 +60,7 @@ import {
60
60
  stringify,
61
61
  toBytes,
62
62
  trim
63
- } from "./chunk-YALGASEU.js";
63
+ } from "./chunk-47PP7TAG.js";
64
64
 
65
65
  // node_modules/.pnpm/abitype@1.2.3_typescript@6.0.3_zod@4.4.3/node_modules/abitype/dist/esm/version.js
66
66
  var version = "1.2.3";
@@ -4796,7 +4796,7 @@ async function call(client, args) {
4796
4796
  if (isAbortError(err))
4797
4797
  throw err;
4798
4798
  const data2 = getRevertErrorData(err);
4799
- const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-XR5NE5QK.js");
4799
+ const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-RPPPKTJR.js");
4800
4800
  if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to)
4801
4801
  return {
4802
4802
  data: await offchainLookup2(client, { data: data2, requestOptions, to })
@@ -5329,4 +5329,4 @@ export {
5329
5329
  ccipRequest,
5330
5330
  call
5331
5331
  };
5332
- //# sourceMappingURL=chunk-ZMHYXMO6.js.map
5332
+ //# sourceMappingURL=chunk-U5S527PP.js.map
@@ -2,12 +2,12 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  HashMD,
4
4
  sha256
5
- } from "./chunk-QVX5MWJZ.js";
5
+ } from "./chunk-W6R3HAAG.js";
6
6
  import {
7
7
  clean,
8
8
  createHasher,
9
9
  rotl
10
- } from "./chunk-5CLSD5YN.js";
10
+ } from "./chunk-KYQVEKP5.js";
11
11
 
12
12
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js
13
13
  var sha2562 = sha256;
@@ -137,4 +137,4 @@ export {
137
137
  sha2562 as sha256,
138
138
  ripemd1602 as ripemd160
139
139
  };
140
- //# sourceMappingURL=chunk-RY4XKNV3.js.map
140
+ //# sourceMappingURL=chunk-UHTVXQ2O.js.map
@@ -35,7 +35,7 @@ import {
35
35
  randomBytes,
36
36
  rotr,
37
37
  toBytes
38
- } from "./chunk-5CLSD5YN.js";
38
+ } from "./chunk-KYQVEKP5.js";
39
39
 
40
40
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
41
41
  function setBigUint64(view, byteOffset, value, isLE) {
@@ -2250,4 +2250,4 @@ export {
2250
2250
  @noble/curves/esm/secp256k1.js:
2251
2251
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2252
2252
  */
2253
- //# sourceMappingURL=chunk-QVX5MWJZ.js.map
2253
+ //# sourceMappingURL=chunk-W6R3HAAG.js.map
@@ -15,4 +15,4 @@ export {
15
15
  ATOMIC_RE,
16
16
  newId
17
17
  };
18
- //# sourceMappingURL=chunk-3OV7E5G5.js.map
18
+ //# sourceMappingURL=chunk-WWX32ML4.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/ids.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\n/**\n * The shared identity patterns for server-controlled values that become file\n * paths, URL segments, or terminal output. One definition so a future change\n * (e.g. accepting uppercase ids) cannot be applied in one command and missed in\n * another. SLUG_RE must match the server's slugify charset (lib/posts.ts:\n * lowercase a-z0-9 groups joined by single hyphens, no leading/trailing hyphen).\n */\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n/** A non-negative atomic USDC integer string (6-decimal base units). */\nexport const ATOMIC_RE = /^\\d{1,39}$/;\n\n/**\n * Mint a fresh opaque id for a locally-created entity (a parked candidate). A v4\n * uuid: the same shape a lookupId takes, so UUID_RE validates it and a `drop\n * <id>` argument that reaches a filesystem path can't traverse out of the store.\n */\nexport function newId(): string {\n return randomUUID();\n}\n"],"mappings":";;;AAAA,SAAS,kBAAkB;AASpB,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,IAAM,YAAY;AAOlB,SAAS,QAAgB;AAC9B,SAAO,WAAW;AACpB;","names":[]}
1
+ {"version":3,"sources":["../src/lib/ids.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\n/**\n * The shared identity patterns for server-controlled values that become file\n * paths, URL segments, or terminal output. One definition so a future change\n * (e.g. accepting uppercase ids) cannot be applied in one command and missed in\n * another. SLUG_RE must match the server's slugify charset (lib/posts.ts:\n * lowercase a-z0-9 groups joined by single hyphens, no leading/trailing hyphen).\n */\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n/** A non-negative atomic USDC integer string (6-decimal base units). */\nexport const ATOMIC_RE = /^\\d{1,39}$/;\n\n/**\n * Mint a fresh opaque id for a locally-created entity (a parked candidate). A v4\n * uuid: the same shape a searchId takes, so UUID_RE validates it and a `drop\n * <id>` argument that reaches a filesystem path can't traverse out of the store.\n */\nexport function newId(): string {\n return randomUUID();\n}\n"],"mappings":";;;AAAA,SAAS,kBAAkB;AASpB,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,IAAM,YAAY;AAOlB,SAAS,QAAgB;AAC9B,SAAO,WAAW;AACpB;","names":[]}
@@ -15,7 +15,7 @@ import {
15
15
  swap32IfBE,
16
16
  toBytes,
17
17
  u32
18
- } from "./chunk-5CLSD5YN.js";
18
+ } from "./chunk-KYQVEKP5.js";
19
19
 
20
20
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
21
21
  var _0n = BigInt(0);
@@ -201,4 +201,4 @@ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
201
201
  export {
202
202
  keccak_256
203
203
  };
204
- //# sourceMappingURL=chunk-HIVZG55D.js.map
204
+ //# sourceMappingURL=chunk-XJN5WUKL.js.map
@@ -1,10 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  keccak_256
4
- } from "./chunk-HIVZG55D.js";
4
+ } from "./chunk-XJN5WUKL.js";
5
5
  import {
6
6
  bytesToHex
7
- } from "./chunk-5CLSD5YN.js";
7
+ } from "./chunk-KYQVEKP5.js";
8
8
  import {
9
9
  __commonJS,
10
10
  __require,
@@ -7803,4 +7803,4 @@ export {
7803
7803
  p2 as p,
7804
7804
  m2 as m
7805
7805
  };
7806
- //# sourceMappingURL=chunk-HSDCI7OV.js.map
7806
+ //# sourceMappingURL=chunk-YLYINX2H.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  package_default
4
- } from "./chunk-FJPLRISB.js";
4
+ } from "./chunk-NJF2WENW.js";
5
5
 
6
6
  // src/lib/http.ts
7
7
  async function fetchJson(url, opts) {
@@ -149,4 +149,4 @@ export {
149
149
  CLIENT_HEADER,
150
150
  trimSlash
151
151
  };
152
- //# sourceMappingURL=chunk-4ONXEEQL.js.map
152
+ //# sourceMappingURL=chunk-ZDY2KY5X.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/http.ts","../src/lib/client-meta.ts","../src/lib/url.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `lookup`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers (doctor sends the X-Tenjin-Client label). */\n headers?: Record<string, string>;\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json';\n status?: number;\n requestId?: string;\n message: string;\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n ...(opts.headers !== undefined ? { headers: opts.headers } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and lookup/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const headers: Record<string, string> = { ...(opts.headers ?? {}) };\n let body: string | undefined;\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n headers['content-type'] = 'application/json';\n }\n if (opts.method === 'POST' || body !== undefined) headers['accept'] ??= 'application/json';\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import pkg from '../../package.json';\n\n/**\n * The `X-Tenjin-Client` value on every B2 request (spec 09 §purchase-attribution):\n * the server classifies views/payments by this label, so a CLI lookup-flow\n * purchase is never mixed with a web checkout. Format `tenjin-cli/<version>`.\n */\nexport const CLIENT_HEADER = `tenjin-cli/${pkg.version}`;\n","/** Drop trailing slashes from a base URL so `${base}/path` never doubles a slash. */\nexport function trimSlash(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n"],"mappings":";;;;;;AAyCA,eAAsB,UAAU,KAAa,MAAkD;AAC7F,QAAM,UAAU,KAAK,aAAa;AAClC,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,WAAW;AAIf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,eAAW,MAAM;AAAA,EACnB,GAAG,KAAK,SAAS;AAEjB,MAAI;AACF,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ,WAAW;AAAA,QACnB,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,MAChE,CAAC;AAAA,IACH,SAAS,KAAK;AAIZ,aAAO,WACH,eAAe,KAAK,KAAK,SAAS,IAClC,EAAE,IAAI,OAAO,MAAM,WAAW,SAAS,cAAc,GAAG,YAAY,aAAa,GAAG,CAAC,GAAG;AAAA,IAC9F;AAEA,UAAM,YAAY,IAAI,QAAQ,IAAI,cAAc,KAAK;AAErD,QAAI,CAAC,IAAI,IAAI;AACX,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ,IAAI;AAAA,QACZ,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,QAC/C,SAAS,cAAc,GAAG,uBAAuB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AAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;;ACvPO,IAAM,gBAAgB,cAAc,gBAAI,OAAO;;;ACN/C,SAAS,UAAU,KAAqB;AAC7C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;","names":[]}
1
+ {"version":3,"sources":["../src/lib/http.ts","../src/lib/client-meta.ts","../src/lib/url.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers (doctor sends the X-Tenjin-Client label). */\n headers?: Record<string, string>;\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json';\n status?: number;\n requestId?: string;\n message: string;\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n ...(opts.headers !== undefined ? { headers: opts.headers } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const headers: Record<string, string> = { ...(opts.headers ?? {}) };\n let body: string | undefined;\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n headers['content-type'] = 'application/json';\n }\n if (opts.method === 'POST' || body !== undefined) headers['accept'] ??= 'application/json';\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import pkg from '../../package.json';\n\n/**\n * The `X-Tenjin-Client` value on every B2 request (spec 09 §purchase-attribution):\n * the server classifies views/payments by this label, so a CLI search-flow\n * purchase is never mixed with a web checkout. Format `tenjin-cli/<version>`.\n */\nexport const CLIENT_HEADER = `tenjin-cli/${pkg.version}`;\n","/** Drop trailing slashes from a base URL so `${base}/path` never doubles a slash. */\nexport function trimSlash(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n"],"mappings":";;;;;;AAyCA,eAAsB,UAAU,KAAa,MAAkD;AAC7F,QAAM,UAAU,KAAK,aAAa;AAClC,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,WAAW;AAIf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,eAAW,MAAM;AAAA,EACnB,GAAG,KAAK,SAAS;AAEjB,MAAI;AACF,QAAI;AAC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IAAI;AAAA,QACZ,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,QAC/C,SAAS,cAAc,GAAG,4CAA4C,aAAa,GAAG,CAAC;AAAA,MACzF;AAAA,IACF;AACA,QAAI;AACJ,QAAI,KAAK,SAAS,GAAG;AACnB,UAAI;AACF,eAAO,KAAK,MAAM,IAAI;AAAA,MACxB,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,IAAI;AAAA,MACZ,QAAQ,CAAC,SAAS,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,MAC3C;AAAA,MACA,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD;AAAA,EACF,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AA8BA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;;ACvPO,IAAM,gBAAgB,cAAc,gBAAI,OAAO;;;ACN/C,SAAS,UAAU,KAAqB;AAC7C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;","names":[]}
@@ -2,16 +2,16 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  UUID_RE,
4
4
  newId
5
- } from "./chunk-3OV7E5G5.js";
5
+ } from "./chunk-WWX32ML4.js";
6
6
  import {
7
7
  hasCode
8
8
  } from "./chunk-2I4QTOLB.js";
9
9
  import {
10
10
  writeFileAtomicExclusive
11
- } from "./chunk-MUBUQVC3.js";
11
+ } from "./chunk-2JQ5JSG6.js";
12
12
  import {
13
13
  external_exports
14
- } from "./chunk-OYMYCW7J.js";
14
+ } from "./chunk-PAUXMRSF.js";
15
15
 
16
16
  // src/lib/candidate-store.ts
17
17
  import { mkdir, readFile, readdir, rm, stat } from "fs/promises";
@@ -20,7 +20,7 @@ var DRAFT_FILE = "draft.md";
20
20
  var META_FILE = "meta.json";
21
21
  var CandidateMetaSchema = external_exports.object({
22
22
  schemaVersion: external_exports.literal(1),
23
- lookupId: external_exports.string(),
23
+ searchId: external_exports.string(),
24
24
  question: external_exports.string().optional(),
25
25
  // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates
26
26
  // sorts newest-first lexicographically on this string, which is only a valid
@@ -43,7 +43,7 @@ async function createCandidate(dataDir, input) {
43
43
  const draftPath = join(dir, DRAFT_FILE);
44
44
  const meta = {
45
45
  schemaVersion: 1,
46
- lookupId: input.lookupId,
46
+ searchId: input.searchId,
47
47
  ...input.question !== void 0 ? { question: input.question } : {},
48
48
  created: input.created,
49
49
  sourceProject: input.sourceProject
@@ -123,4 +123,4 @@ export {
123
123
  listCandidates,
124
124
  dropCandidate
125
125
  };
126
- //# sourceMappingURL=chunk-TLCMMYLY.js.map
126
+ //# sourceMappingURL=chunk-ZIYVN4CD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/candidate-store.ts"],"sourcesContent":["import { mkdir, readFile, readdir, rm, stat } from 'node:fs/promises';\nimport type { Dirent } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { hasCode } from './errno';\nimport { newId, UUID_RE } from './ids';\n\n/**\n * The D40 candidate store: publish drafts parked locally that never touch the\n * network and never upload — only a later `tenjin publish --candidate <id>`\n * sends one, under the D38 consent scan. Each candidate is its OWN directory\n * `~/.tenjin/candidates/<id>/` holding the draft markdown plus a meta.json.\n *\n * Custody mirrors the wallet key discipline: the candidates tree is 0700 and\n * every file 0600, written create-once through writeFileAtomicExclusive so a\n * reader sees a complete file or none and a uuid collision is loud, never a\n * silent overwrite. Unlike search-store's single shared ledger, there is no shared\n * mutable file here — a fresh uuid per add means two concurrent adds land in two\n * distinct dirs and cannot contend — so no cross-process lock is needed. The\n * meta.json is written LAST and atomically, making it the commit point: `list`\n * skips any dir whose meta is absent or unreadable, so a torn or half-written\n * add reads as not-yet-there rather than a broken candidate, the same\n * best-effort posture loadSearches takes on a corrupt store. A crash mid-add is\n * cleaned up eagerly (the dir is removed on any write failure), and `drop` can\n * still remove a metaless orphan by id so a leaked draft is never stranded.\n */\n\nconst DRAFT_FILE = 'draft.md';\nconst META_FILE = 'meta.json';\n\nconst CandidateMetaSchema = z.object({\n schemaVersion: z.literal(1),\n searchId: z.string(),\n question: z.string().optional(),\n // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates\n // sorts newest-first lexicographically on this string, which is only a valid\n // proxy for chronological order when every value is same-zone UTC. z.iso\n // .datetime() rejects offsets and non-datetime strings, pinning that invariant.\n created: z.iso.datetime(),\n /** The repo root the add ran in, or the cwd when not in a repo. */\n sourceProject: z.string(),\n});\nexport type CandidateMeta = z.infer<typeof CandidateMetaSchema>;\n\nexport interface CandidateRecord {\n id: string;\n meta: CandidateMeta;\n /** Absolute path of the candidate directory. */\n dir: string;\n /** Absolute path of the draft markdown inside the directory. */\n draftPath: string;\n}\n\nexport interface CreateCandidateInput {\n /** The draft markdown, copied verbatim into the candidate. */\n draft: string;\n searchId: string;\n question?: string;\n /** ISO-8601 creation time; the command supplies it via its clock seam. */\n created: string;\n sourceProject: string;\n}\n\nfunction candidatesDir(dataDir: string): string {\n return join(dataDir, 'candidates');\n}\n\nfunction candidateDir(dataDir: string, id: string): string {\n return join(candidatesDir(dataDir), id);\n}\n\n/** Park a draft as a new candidate and return the created record. Both files are\n * written create-once (no-clobber, fsynced) at a fresh uuid path, meta.json\n * last, so the candidate is either fully present to `list`/`read` or absent,\n * never half-there. */\nexport async function createCandidate(\n dataDir: string,\n input: CreateCandidateInput,\n): Promise<CandidateRecord> {\n const id = newId();\n const dir = candidateDir(dataDir, id);\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const draftPath = join(dir, DRAFT_FILE);\n const meta: CandidateMeta = {\n schemaVersion: 1,\n searchId: input.searchId,\n ...(input.question !== undefined ? { question: input.question } : {}),\n created: input.created,\n sourceProject: input.sourceProject,\n };\n try {\n // Exclusive (create-or-EEXIST, fsynced) so a uuid collision is loud, not a\n // silent overwrite of an existing candidate, and the crash-durable commit of\n // meta.json is the last, atomic step.\n await writeFileAtomicExclusive(draftPath, input.draft, { mode: 0o600, dirMode: 0o700 });\n await writeFileAtomicExclusive(join(dir, META_FILE), `${JSON.stringify(meta, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n // An EEXIST means something already lived at this fresh-uuid path (a real\n // collision, astronomically unlikely): surface it loudly and NEVER delete\n // what was already there. Any other failure is a partial write of our own\n // fresh dir — remove it so a crash mid-add can't strand a hidden dir holding\n // the (secrets-adjacent) draft that `list` skips and no one can name to `drop`.\n if (!hasCode(err, 'EEXIST')) {\n await rm(dir, { recursive: true, force: true }).catch(() => undefined);\n }\n throw err;\n }\n\n return { id, meta, dir, draftPath };\n}\n\n/** One candidate by id, or null when it is unknown (or the id is malformed, so a\n * stray argument can never traverse out of the store). */\nexport async function readCandidate(dataDir: string, id: string): Promise<CandidateRecord | null> {\n if (!UUID_RE.test(id)) return null;\n const dir = candidateDir(dataDir, id);\n const meta = await readMeta(dir);\n if (meta === null) return null;\n return { id, meta, dir, draftPath: join(dir, DRAFT_FILE) };\n}\n\n/** Every pending candidate, newest first by `created` (no auto-expiry — stale\n * candidates stay visible, D40). Tie-broken on id so the order is total. */\nexport async function listCandidates(dataDir: string): Promise<CandidateRecord[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(candidatesDir(dataDir), { withFileTypes: true });\n } catch {\n return [];\n }\n const records: CandidateRecord[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || !UUID_RE.test(entry.name)) continue;\n const record = await readCandidate(dataDir, entry.name);\n if (record !== null) records.push(record);\n }\n records.sort((a, b) => {\n if (a.meta.created !== b.meta.created) return a.meta.created < b.meta.created ? 1 : -1;\n return a.id < b.id ? 1 : -1;\n });\n return records;\n}\n\n/** Discard one candidate by id. Returns false when the id is malformed or no\n * such dir exists, so the command can surface a clean not-found; nothing is\n * ever auto-deleted. Removes the dir even when its meta is absent or corrupt,\n * so a crash-orphaned candidate can still be cleaned up by id (the id is\n * UUID-gated first, so a stray argument can never target a path outside the\n * store). */\nexport async function dropCandidate(dataDir: string, id: string): Promise<boolean> {\n if (!UUID_RE.test(id)) return false;\n const dir = candidateDir(dataDir, id);\n try {\n if (!(await stat(dir)).isDirectory()) return false;\n } catch {\n return false; // no such candidate\n }\n await rm(dir, { recursive: true, force: true });\n return true;\n}\n\n/** Read and validate a candidate's meta.json; null on any absence/corruption. */\nasync function readMeta(dir: string): Promise<CandidateMeta | null> {\n let raw: string;\n try {\n raw = await readFile(join(dir, META_FILE), 'utf8');\n } catch {\n return null;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return null;\n }\n const parsed = CandidateMetaSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,SAAS,IAAI,YAAY;AAEnD,SAAS,YAAY;AA0BrB,IAAM,aAAa;AACnB,IAAM,YAAY;AAElB,IAAM,sBAAsB,iBAAE,OAAO;AAAA,EACnC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,UAAU,iBAAE,OAAO;AAAA,EACnB,UAAU,iBAAE,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9B,SAAS,iBAAE,IAAI,SAAS;AAAA;AAAA,EAExB,eAAe,iBAAE,OAAO;AAC1B,CAAC;AAsBD,SAAS,cAAc,SAAyB;AAC9C,SAAO,KAAK,SAAS,YAAY;AACnC;AAEA,SAAS,aAAa,SAAiB,IAAoB;AACzD,SAAO,KAAK,cAAc,OAAO,GAAG,EAAE;AACxC;AAMA,eAAsB,gBACpB,SACA,OAC0B;AAC1B,QAAM,KAAK,MAAM;AACjB,QAAM,MAAM,aAAa,SAAS,EAAE;AACpC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,MAAM,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AAQ,KAAK,MAAM,IAAI,EAAG;AACvD,UAAM,SAAS,MAAM,cAAc,SAAS,MAAM,IAAI;AACtD,QAAI,WAAW,KAAM,SAAQ,KAAK,MAAM;AAAA,EAC1C;AACA,UAAQ,KAAK,CAAC,GAAG,MAAM;AACrB,QAAI,EAAE,KAAK,YAAY,EAAE,KAAK,QAAS,QAAO,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,IAAI;AACpF,WAAO,EAAE,KAAK,EAAE,KAAK,IAAI;AAAA,EAC3B,CAAC;AACD,SAAO;AACT;AAQA,eAAsB,cAAc,SAAiB,IAA8B;AACjF,MAAI,CAAC,QAAQ,KAAK,EAAE,EAAG,QAAO;AAC9B,QAAM,MAAM,aAAa,SAAS,EAAE;AACpC,MAAI;AACF,QAAI,EAAE,MAAM,KAAK,GAAG,GAAG,YAAY,EAAG,QAAO;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,GAAG,KAAK,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAC9C,SAAO;AACT;AAGA,eAAe,SAAS,KAA4C;AAClE,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,KAAK,KAAK,SAAS,GAAG,MAAM;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,oBAAoB,UAAU,IAAI;AACjD,SAAO,OAAO,UAAU,OAAO,OAAO;AACxC;","names":[]}
@@ -3,32 +3,27 @@ import {
3
3
  createCandidate,
4
4
  dropCandidate,
5
5
  listCandidates
6
- } from "./chunk-TLCMMYLY.js";
6
+ } from "./chunk-ZIYVN4CD.js";
7
7
  import {
8
8
  UUID_RE
9
- } from "./chunk-3OV7E5G5.js";
9
+ } from "./chunk-WWX32ML4.js";
10
10
  import {
11
11
  sanitizeForTerminal
12
- } from "./chunk-Z52RA3NC.js";
12
+ } from "./chunk-NFSOVL3C.js";
13
13
  import {
14
14
  pathExists
15
- } from "./chunk-GO75V3NZ.js";
16
- import "./chunk-ESPNTPQ2.js";
17
- import "./chunk-2I4QTOLB.js";
18
- import "./chunk-UO22YNY4.js";
19
- import "./chunk-MUBUQVC3.js";
15
+ } from "./chunk-MDDGEGSW.js";
20
16
  import {
21
17
  CliError
22
- } from "./chunk-OYMYCW7J.js";
23
- import "./chunk-ZXTAQYNA.js";
18
+ } from "./chunk-PAUXMRSF.js";
24
19
 
25
20
  // src/commands/candidate.ts
26
21
  import { readFile } from "fs/promises";
27
22
  import { dirname, join, resolve } from "path";
28
23
  async function runCandidateAdd(args, ctx, deps = {}) {
29
- if (!UUID_RE.test(args.lookupId)) {
30
- throw new CliError("USAGE", `Invalid --lookup-id: ${JSON.stringify(args.lookupId)}.`, {
31
- fix: "Pass the lookupId from a prior `tenjin lookup` (a uuid)."
24
+ if (!UUID_RE.test(args.searchId)) {
25
+ throw new CliError("USAGE", `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {
26
+ fix: "Pass the searchId from a prior `tenjin search` (a uuid)."
32
27
  });
33
28
  }
34
29
  if (args.question !== void 0 && args.question.length > 200) {
@@ -50,7 +45,7 @@ async function runCandidateAdd(args, ctx, deps = {}) {
50
45
  const created = (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
51
46
  const record = await createCandidate(ctx.dataDir, {
52
47
  draft,
53
- lookupId: args.lookupId,
48
+ searchId: args.searchId,
54
49
  ...args.question !== void 0 ? { question: args.question } : {},
55
50
  created,
56
51
  sourceProject
@@ -59,7 +54,7 @@ async function runCandidateAdd(args, ctx, deps = {}) {
59
54
  data: {
60
55
  id: record.id,
61
56
  path: record.dir,
62
- lookupId: record.meta.lookupId,
57
+ searchId: record.meta.searchId,
63
58
  ...record.meta.question !== void 0 ? { question: record.meta.question } : {},
64
59
  created: record.meta.created,
65
60
  sourceProject: record.meta.sourceProject
@@ -72,7 +67,7 @@ async function runCandidateList(ctx, deps = {}) {
72
67
  const records = await listCandidates(ctx.dataDir);
73
68
  const candidates = records.map((r) => ({
74
69
  id: r.id,
75
- lookupId: r.meta.lookupId,
70
+ searchId: r.meta.searchId,
76
71
  ...r.meta.question !== void 0 ? { question: r.meta.question } : {},
77
72
  created: r.meta.created,
78
73
  sourceProject: r.meta.sourceProject,
@@ -119,9 +114,10 @@ function humanizeAge(iso, now) {
119
114
  if (ms < DAY) return `${Math.floor(ms / HOUR)}h ago`;
120
115
  return `${Math.floor(ms / DAY)}d ago`;
121
116
  }
117
+
122
118
  export {
123
119
  runCandidateAdd,
124
- runCandidateDrop,
125
- runCandidateList
120
+ runCandidateList,
121
+ runCandidateDrop
126
122
  };
127
- //# sourceMappingURL=candidate-ERMSYYQZ.js.map
123
+ //# sourceMappingURL=chunk-ZW3B5LWX.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/candidate.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { createCandidate, dropCandidate, listCandidates } from '../lib/candidate-store';\nimport { UUID_RE } from '../lib/ids';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { pathExists } from '../lib/settings';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin candidate [add|list|drop]`: the D40 local store of parked publish\n * drafts. Entirely offline — a candidate never touches the network and never\n * uploads; only a later `tenjin publish --candidate <id>` sends it, under the\n * D38 consent scan. This module owns the command surface; lib/candidate-store.ts\n * owns the on-disk custody (0700 dirs, 0600 files, atomic meta commit).\n */\n\nexport interface CandidateAddArgs {\n file: string;\n lookupId: string;\n question?: string;\n}\n\nexport interface CandidateDeps {\n /** Clock seam so list ordering / age tests are deterministic. */\n now?: () => Date;\n /** cwd seam so sourceProject discovery is testable against a temp tree. */\n cwd?: string;\n}\n\nexport async function runCandidateAdd(\n args: CandidateAddArgs,\n ctx: CommandContext,\n deps: CandidateDeps = {},\n): Promise<CommandResult> {\n if (!UUID_RE.test(args.lookupId)) {\n throw new CliError('USAGE', `Invalid --lookup-id: ${JSON.stringify(args.lookupId)}.`, {\n fix: 'Pass the lookupId from a prior `tenjin lookup` (a uuid).',\n });\n }\n // Cap the question at the server's questionsAnswered item bound (200) at PARK\n // time, so a candidate can never be born unpublishable — it prefills the card's\n // questionsAnswered, which publish would otherwise reject only at write time.\n if (args.question !== undefined && args.question.length > 200) {\n throw new CliError('USAGE', 'A candidate --question is at most 200 characters.', {\n fix: 'Shorten the question to 200 characters or fewer.',\n });\n }\n\n let draft: string;\n try {\n draft = await readFile(args.file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Cannot read draft file ${JSON.stringify(args.file)}.`, {\n fix: 'Pass a path to a readable Markdown file.',\n cause: err,\n });\n }\n\n const cwd = deps.cwd ?? process.cwd();\n const sourceProject = await repoRootOrCwd(cwd);\n const created = (deps.now?.() ?? new Date()).toISOString();\n\n const record = await createCandidate(ctx.dataDir, {\n draft,\n lookupId: args.lookupId,\n ...(args.question !== undefined ? { question: args.question } : {}),\n created,\n sourceProject,\n });\n\n return {\n data: {\n id: record.id,\n path: record.dir,\n lookupId: record.meta.lookupId,\n ...(record.meta.question !== undefined ? { question: record.meta.question } : {}),\n created: record.meta.created,\n sourceProject: record.meta.sourceProject,\n },\n humanLines: [`Parked candidate ${record.id}`, ` ${record.dir}`],\n };\n}\n\nexport async function runCandidateList(\n ctx: CommandContext,\n deps: CandidateDeps = {},\n): Promise<CommandResult> {\n const now = deps.now?.() ?? new Date();\n const records = await listCandidates(ctx.dataDir);\n\n const candidates = records.map((r) => ({\n id: r.id,\n lookupId: r.meta.lookupId,\n ...(r.meta.question !== undefined ? { question: r.meta.question } : {}),\n created: r.meta.created,\n sourceProject: r.meta.sourceProject,\n path: r.dir,\n }));\n\n const humanLines =\n records.length === 0\n ? ['No pending candidates.']\n : records.map((r) => {\n const q =\n r.meta.question !== undefined ? sanitizeForTerminal(r.meta.question) : '(no question)';\n return `${r.id} ${humanizeAge(r.meta.created, now)} ${q} [${sanitizeForTerminal(\n r.meta.sourceProject,\n )}]`;\n });\n\n return { data: { candidates }, humanLines };\n}\n\nexport async function runCandidateDrop(\n args: { id: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n const dropped = await dropCandidate(ctx.dataDir, args.id);\n if (!dropped) {\n throw new CliError('USAGE', `No candidate with id ${JSON.stringify(args.id)}.`, {\n fix: 'Run `tenjin candidate list` to see pending candidate ids.',\n });\n }\n return {\n data: { id: args.id, dropped: true },\n humanLines: [`Dropped candidate ${args.id}.`],\n };\n}\n\n/**\n * The project a candidate was parked from: the nearest ancestor holding a `.git`\n * (inclusive), or the cwd when the add did not run inside a repo. Mirrors the\n * repo-root walk settings.ts uses to bound the `.tenjin.json` search.\n */\nasync function repoRootOrCwd(cwd: string): Promise<string> {\n let dir = resolve(cwd);\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return resolve(cwd);\n dir = parent;\n }\n}\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/**\n * Compact relative age for the human list (\"just now\", \"5m ago\", \"3d ago\"). A\n * future or unparseable timestamp degrades to \"just now\" rather than throwing;\n * the ISO value is always carried verbatim in the JSON data for machines.\n */\nfunction humanizeAge(iso: string, now: Date): string {\n const then = Date.parse(iso);\n if (Number.isNaN(then)) return 'just now';\n const ms = now.getTime() - then;\n if (ms < MINUTE) return 'just now';\n if (ms < HOUR) return `${Math.floor(ms / MINUTE)}m ago`;\n if (ms < DAY) return `${Math.floor(ms / HOUR)}h ago`;\n return `${Math.floor(ms / DAY)}d ago`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,MAAM,eAAe;AA6BvC,eAAsB,gBACpB,MACA,KACA,OAAsB,CAAC,GACC;AACxB,MAAI,CAAC,QAAQ,KAAK,KAAK,Q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ChD,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK,QAAO,QAAQ,GAAG;AACtC,UAAM;AAAA,EACR;AACF;AAEA,IAAM,SAAS;AACf,IAAM,OAAO,KAAK;AAClB,IAAM,MAAM,KAAK;AAOjB,SAAS,YAAY,KAAa,KAAmB;AACnD,QAAM,OAAO,KAAK,MAAM,GAAG;AAC3B,MAAI,OAAO,MAAM,IAAI,EAAG,QAAO;AAC/B,QAAM,KAAK,IAAI,QAAQ,IAAI;AAC3B,MAAI,KAAK,OAAQ,QAAO;AACxB,MAAI,KAAK,KAAM,QAAO,GAAG,KAAK,MAAM,KAAK,MAAM,CAAC;AAChD,MAAI,KAAK,IAAK,QAAO,GAAG,KAAK,MAAM,KAAK,IAAI,CAAC;AAC7C,SAAO,GAAG,KAAK,MAAM,KAAK,GAAG,CAAC;AAChC;","names":[]}
1
+ {"version":3,"sources":["../src/commands/candidate.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { createCandidate, dropCandidate, listCandidates } from '../lib/candidate-store';\nimport { UUID_RE } from '../lib/ids';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { pathExists } from '../lib/settings';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin candidate [add|list|drop]`: the D40 local store of parked publish\n * drafts. Entirely offline — a candidate never touches the network and never\n * uploads; only a later `tenjin publish --candidate <id>` sends it, under the\n * D38 consent scan. This module owns the command surface; lib/candidate-store.ts\n * owns the on-disk custody (0700 dirs, 0600 files, atomic meta commit).\n */\n\nexport interface CandidateAddArgs {\n file: string;\n searchId: string;\n question?: string;\n}\n\nexport interface CandidateDeps {\n /** Clock seam so list ordering / age tests are deterministic. */\n now?: () => Date;\n /** cwd seam so sourceProject discovery is testable against a temp tree. */\n cwd?: string;\n}\n\nexport async function runCandidateAdd(\n args: CandidateAddArgs,\n ctx: CommandContext,\n deps: CandidateDeps = {},\n): Promise<CommandResult> {\n if (!UUID_RE.test(args.searchId)) {\n throw new CliError('USAGE', `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {\n fix: 'Pass the searchId from a prior `tenjin search` (a uuid).',\n });\n }\n // Cap the question at the server's questionsAnswered item bound (200) at PARK\n // time, so a candidate can never be born unpublishable — it prefills the card's\n // questionsAnswered, which publish would otherwise reject only at write time.\n if (args.question !== undefined && args.question.length > 200) {\n throw new CliError('USAGE', 'A candidate --question is at most 200 characters.', {\n fix: 'Shorten the question to 200 characters or fewer.',\n });\n }\n\n let draft: string;\n try {\n draft = await readFile(args.file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Cannot read draft file ${JSON.stringify(args.file)}.`, {\n fix: 'Pass a path to a readable Markdown file.',\n cause: err,\n });\n }\n\n const cwd = deps.cwd ?? process.cwd();\n const sourceProject = await repoRootOrCwd(cwd);\n const created = (deps.now?.() ?? new Date()).toISOString();\n\n const record = await createCandidate(ctx.dataDir, {\n draft,\n searchId: args.searchId,\n ...(args.question !== undefined ? { question: args.question } : {}),\n created,\n sourceProject,\n });\n\n return {\n data: {\n id: record.id,\n path: record.dir,\n searchId: record.meta.searchId,\n ...(record.meta.question !== undefined ? { question: record.meta.question } : {}),\n created: record.meta.created,\n sourceProject: record.meta.sourceProject,\n },\n humanLines: [`Parked candidate ${record.id}`, ` ${record.dir}`],\n };\n}\n\nexport async function runCandidateList(\n ctx: CommandContext,\n deps: CandidateDeps = {},\n): Promise<CommandResult> {\n const now = deps.now?.() ?? new Date();\n const records = await listCandidates(ctx.dataDir);\n\n const candidates = records.map((r) => ({\n id: r.id,\n searchId: r.meta.searchId,\n ...(r.meta.question !== undefined ? { question: r.meta.question } : {}),\n created: r.meta.created,\n sourceProject: r.meta.sourceProject,\n path: r.dir,\n }));\n\n const humanLines =\n records.length === 0\n ? ['No pending candidates.']\n : records.map((r) => {\n const q =\n r.meta.question !== undefined ? sanitizeForTerminal(r.meta.question) : '(no question)';\n return `${r.id} ${humanizeAge(r.meta.created, now)} ${q} [${sanitizeForTerminal(\n r.meta.sourceProject,\n )}]`;\n });\n\n return { data: { candidates }, humanLines };\n}\n\nexport async function runCandidateDrop(\n args: { id: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n const dropped = await dropCandidate(ctx.dataDir, args.id);\n if (!dropped) {\n throw new CliError('USAGE', `No candidate with id ${JSON.stringify(args.id)}.`, {\n fix: 'Run `tenjin candidate list` to see pending candidate ids.',\n });\n }\n return {\n data: { id: args.id, dropped: true },\n humanLines: [`Dropped candidate ${args.id}.`],\n };\n}\n\n/**\n * The project a candidate was parked from: the nearest ancestor holding a `.git`\n * (inclusive), or the cwd when the add did not run inside a repo. Mirrors the\n * repo-root walk settings.ts uses to bound the `.tenjin.json` search.\n */\nasync function repoRootOrCwd(cwd: string): Promise<string> {\n let dir = resolve(cwd);\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return resolve(cwd);\n dir = parent;\n }\n}\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/**\n * Compact relative age for the human list (\"just now\", \"5m ago\", \"3d ago\"). A\n * future or unparseable timestamp degrades to \"just now\" rather than throwing;\n * the ISO value is always carried verbatim in the JSON data for machines.\n */\nfunction humanizeAge(iso: string, now: Date): string {\n const then = Date.parse(iso);\n if (Number.isNaN(then)) return 'just now';\n const ms = now.getTime() - then;\n if (ms < MINUTE) return 'just now';\n if (ms < HOUR) return `${Math.floor(ms / MINUTE)}m ago`;\n if (ms < DAY) return `${Math.floor(ms / HOUR)}h ago`;\n return `${Math.floor(ms / DAY)}d ago`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,MAAM,eAAe;AA6BvC,eAAsB,gBACpB,MACA,KACA,OAAsB,CAAC,GACC;AACxB,MAAI,CAAC,QAAQ,KAAK,KAAK,QAAQ,GAAG;AACh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