tenjin-cli 0.1.0-alpha.24 → 0.1.0-alpha.25

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 (114) hide show
  1. package/README.md +5 -1
  2. package/dist/{chunk-H5UR3GFJ.js → chunk-3ZYPVSIU.js} +56 -31
  3. package/dist/chunk-3ZYPVSIU.js.map +1 -0
  4. package/dist/chunk-7EKYXMUO.js +7536 -0
  5. package/dist/chunk-7EKYXMUO.js.map +1 -0
  6. package/dist/chunk-AKWGE6JQ.js +49 -0
  7. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  8. package/dist/{chunk-RCJ64OXH.js → chunk-CEMXMUIU.js} +3 -3
  9. package/dist/{chunk-XZUGRTSV.js → chunk-CKDD554V.js} +2 -2
  10. package/dist/{hook-command-GMIDXVFK.js → chunk-CP7O6M55.js} +190 -40
  11. package/dist/chunk-CP7O6M55.js.map +1 -0
  12. package/dist/{chunk-UBOFYC6J.js → chunk-DRXDTITB.js} +1821 -141
  13. package/dist/chunk-DRXDTITB.js.map +1 -0
  14. package/dist/{chunk-EP5P2STS.js → chunk-EACMJEF3.js} +201 -8
  15. package/dist/chunk-EACMJEF3.js.map +1 -0
  16. package/dist/{chunk-GPLSNGKX.js → chunk-EG7P4SM6.js} +4 -4
  17. package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
  18. package/dist/chunk-EL56RW2J.js.map +1 -0
  19. package/dist/{chunk-KC24CYGV.js → chunk-EOGJKIOG.js} +6 -8
  20. package/dist/{chunk-KC24CYGV.js.map → chunk-EOGJKIOG.js.map} +1 -1
  21. package/dist/{chunk-ZMFDMALH.js → chunk-GT6W3VJM.js} +2 -2
  22. package/dist/{chunk-TMLCEPCD.js → chunk-HII5HOQV.js} +3 -5
  23. package/dist/chunk-HII5HOQV.js.map +1 -0
  24. package/dist/{chunk-UXSF7IFD.js → chunk-IYLECN4D.js} +3 -3
  25. package/dist/{chunk-SQSKVKX6.js → chunk-KGTQRJGS.js} +17 -8
  26. package/dist/chunk-KGTQRJGS.js.map +1 -0
  27. package/dist/chunk-LFZJM56J.js +159 -0
  28. package/dist/chunk-LFZJM56J.js.map +1 -0
  29. package/dist/{chunk-YZTIYDWU.js → chunk-NTYQHAIM.js} +2 -2
  30. package/dist/{chunk-IIE65SJC.js → chunk-NYPFOHSJ.js} +4 -4
  31. package/dist/{chunk-ZNZGBUV6.js → chunk-ODH7UXIS.js} +8 -7
  32. package/dist/chunk-ODH7UXIS.js.map +1 -0
  33. package/dist/{chunk-NSDZESRS.js → chunk-OZ3LWLCI.js} +3 -3
  34. package/dist/{chunk-XRW4N23F.js → chunk-SCAE6PW6.js} +4 -4
  35. package/dist/{chunk-O2WN732M.js → chunk-UDWGT4FX.js} +2 -2
  36. package/dist/chunk-VYONGSMQ.js +119 -0
  37. package/dist/chunk-VYONGSMQ.js.map +1 -0
  38. package/dist/{chunk-P22ZWXFX.js → chunk-XICKN3CH.js} +49 -4
  39. package/dist/chunk-XICKN3CH.js.map +1 -0
  40. package/dist/chunk-YHKXNYTB.js +105 -0
  41. package/dist/chunk-YHKXNYTB.js.map +1 -0
  42. package/dist/{chunk-W2ARIOAZ.js → chunk-YSW57KUT.js} +8 -10
  43. package/dist/{chunk-W2ARIOAZ.js.map → chunk-YSW57KUT.js.map} +1 -1
  44. package/dist/{chunk-FFL5M5BC.js → chunk-YTM7OURD.js} +2 -2
  45. package/dist/{cli-GGNOQQEB.js → cli-4WMGZPBP.js} +27 -28
  46. package/dist/{cli-GGNOQQEB.js.map → cli-4WMGZPBP.js.map} +1 -1
  47. package/dist/{config-XUUFICXK.js → config-VU6U7QOU.js} +9 -8
  48. package/dist/{doctor-3LGF6CWI.js → doctor-26JS2SG3.js} +123 -31
  49. package/dist/doctor-26JS2SG3.js.map +1 -0
  50. package/dist/{fund-3URFMBMN.js → fund-JJN3FRRF.js} +13 -14
  51. package/dist/fund-JJN3FRRF.js.map +1 -0
  52. package/dist/hook-command-S2V4UNB3.js +28 -0
  53. package/dist/index.js +3 -3
  54. package/dist/{install-FRTG4KHF.js → install-GXQ33J4G.js} +19 -16
  55. package/dist/{install-identity-WNXSYP6N.js → install-identity-HFQUXPSI.js} +6 -7
  56. package/dist/{install-wallet-MXLJJP3N.js → install-wallet-27LTEHBI.js} +8 -9
  57. package/dist/{install-wallet-MXLJJP3N.js.map → install-wallet-27LTEHBI.js.map} +1 -1
  58. package/dist/{mcp-O2WJ3QBW.js → mcp-AHCZVD2U.js} +596 -75
  59. package/dist/mcp-AHCZVD2U.js.map +1 -0
  60. package/dist/{pay-43WUYTW5.js → pay-3TCOPGCX.js} +14 -13
  61. package/dist/{payments-7UTMMTIO.js → payments-H3LSBGSL.js} +6 -7
  62. package/dist/{payments-7UTMMTIO.js.map → payments-H3LSBGSL.js.map} +1 -1
  63. package/dist/{send-ALHG2RXT.js → send-LKCLN5GA.js} +9 -11
  64. package/dist/{send-ALHG2RXT.js.map → send-LKCLN5GA.js.map} +1 -1
  65. package/dist/{status-CFPNHB6R.js → status-2FDGI4LQ.js} +7 -9
  66. package/dist/{status-CFPNHB6R.js.map → status-2FDGI4LQ.js.map} +1 -1
  67. package/dist/{status-line-FJ6N7MKJ.js → status-line-QKDJYZGV.js} +4 -5
  68. package/dist/{status-line-FJ6N7MKJ.js.map → status-line-QKDJYZGV.js.map} +1 -1
  69. package/dist/{status-line-wiring-GXFNXHPE.js → status-line-wiring-ZDBYHNYR.js} +6 -4
  70. package/dist/{uninstall-5P2GFYBY.js → uninstall-ZXWABDHS.js} +33 -29
  71. package/dist/uninstall-ZXWABDHS.js.map +1 -0
  72. package/dist/{update-QJ5YHJ7I.js → update-HEIWVOP5.js} +17 -6
  73. package/dist/update-HEIWVOP5.js.map +1 -0
  74. package/dist/{wallet-6OJPGNEV.js → wallet-T7JYWI6O.js} +8 -9
  75. package/dist/wallet-T7JYWI6O.js.map +1 -0
  76. package/docs/agent-permissions.md +6 -3
  77. package/package.json +7 -6
  78. package/dist/chunk-EP5P2STS.js.map +0 -1
  79. package/dist/chunk-H5UR3GFJ.js.map +0 -1
  80. package/dist/chunk-O2JYBOUO.js +0 -47
  81. package/dist/chunk-O2JYBOUO.js.map +0 -1
  82. package/dist/chunk-P22ZWXFX.js.map +0 -1
  83. package/dist/chunk-RGVOODF4.js.map +0 -1
  84. package/dist/chunk-S2NRVRPF.js +0 -171
  85. package/dist/chunk-S2NRVRPF.js.map +0 -1
  86. package/dist/chunk-SQSKVKX6.js.map +0 -1
  87. package/dist/chunk-TMLCEPCD.js.map +0 -1
  88. package/dist/chunk-UBOFYC6J.js.map +0 -1
  89. package/dist/chunk-YXLG7Q6Q.js +0 -140
  90. package/dist/chunk-YXLG7Q6Q.js.map +0 -1
  91. package/dist/chunk-ZNZGBUV6.js.map +0 -1
  92. package/dist/doctor-3LGF6CWI.js.map +0 -1
  93. package/dist/fund-3URFMBMN.js.map +0 -1
  94. package/dist/hook-command-GMIDXVFK.js.map +0 -1
  95. package/dist/mcp-O2WJ3QBW.js.map +0 -1
  96. package/dist/uninstall-5P2GFYBY.js.map +0 -1
  97. package/dist/update-QJ5YHJ7I.js.map +0 -1
  98. /package/dist/{chunk-RCJ64OXH.js.map → chunk-CEMXMUIU.js.map} +0 -0
  99. /package/dist/{chunk-XZUGRTSV.js.map → chunk-CKDD554V.js.map} +0 -0
  100. /package/dist/{chunk-GPLSNGKX.js.map → chunk-EG7P4SM6.js.map} +0 -0
  101. /package/dist/{chunk-ZMFDMALH.js.map → chunk-GT6W3VJM.js.map} +0 -0
  102. /package/dist/{chunk-UXSF7IFD.js.map → chunk-IYLECN4D.js.map} +0 -0
  103. /package/dist/{chunk-YZTIYDWU.js.map → chunk-NTYQHAIM.js.map} +0 -0
  104. /package/dist/{chunk-IIE65SJC.js.map → chunk-NYPFOHSJ.js.map} +0 -0
  105. /package/dist/{chunk-NSDZESRS.js.map → chunk-OZ3LWLCI.js.map} +0 -0
  106. /package/dist/{chunk-XRW4N23F.js.map → chunk-SCAE6PW6.js.map} +0 -0
  107. /package/dist/{chunk-O2WN732M.js.map → chunk-UDWGT4FX.js.map} +0 -0
  108. /package/dist/{chunk-FFL5M5BC.js.map → chunk-YTM7OURD.js.map} +0 -0
  109. /package/dist/{config-XUUFICXK.js.map → config-VU6U7QOU.js.map} +0 -0
  110. /package/dist/{install-FRTG4KHF.js.map → hook-command-S2V4UNB3.js.map} +0 -0
  111. /package/dist/{install-identity-WNXSYP6N.js.map → install-GXQ33J4G.js.map} +0 -0
  112. /package/dist/{pay-43WUYTW5.js.map → install-identity-HFQUXPSI.js.map} +0 -0
  113. /package/dist/{status-line-wiring-GXFNXHPE.js.map → pay-3TCOPGCX.js.map} +0 -0
  114. /package/dist/{wallet-6OJPGNEV.js.map → status-line-wiring-ZDBYHNYR.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/config.ts","../src/lib/skill-wiring.ts","../src/lib/skills-source.ts","../src/lib/harness-presence.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname } from 'node:path';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport type { CodexGrantResult } from '../lib/harness-permissions';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from '../lib/production-origin';\nimport {\n CONFIG_KEYS,\n RETIRED_PAYMENT_GUIDANCE,\n retiredPaymentKeys,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n LOOP_CONFIG_KEYS,\n TEAM_CONFIG_KEYS,\n EXPERIMENTAL_CONFIG_KEYS,\n ROUTER_CONFIG_KEYS,\n ROUTER_CONTEXTS,\n loadRawConfig,\n parseLoopValue,\n parsePublicFallbackFlag,\n parseAckServerWarnings,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HookArm,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n UpdateConfigKey,\n LoopConfigKey,\n TeamConfigKey,\n ExperimentalConfigKey,\n RouterConfigKey,\n RouterContext,\n} from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { Harness, HarnessAdapter } from '../adapters/types';\nimport { ADAPTERS } from '../adapters/registry';\nimport { isTeamShelfOrigin, loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { installedHarnessInPlay } from '../lib/harness-presence';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\nimport {\n projectRouterPath,\n readProjectRouterFile,\n routerSettings,\n type RouterSettings,\n} from '../router/settings';\n\n/** Machine values use Money for spending keys and scalars for other settings. */\ninterface RenderedValue {\n value: Money | string | string[] | boolean | null;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n /** The file a router key came from, when one did. */\n path?: string;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Harness lifecycle implementations; tests inject adapters at this boundary. */\n adapters?: Readonly<Record<Harness, HarnessAdapter>>;\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Settled harness selection; absent, each registered adapter is detected normally. */\n harnessesInPlay?: readonly Harness[];\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\n/**\n * The shelf's settings. `config get/set` still accept them and `--json` still\n * carries them, but the human listing shows only what the router CLI uses: it\n * ships no shelf command that reads these.\n */\nconst SHELF_KEYS: ReadonlySet<string> = new Set<string>([\n 'allowlistCreators',\n 'publicShelfUrl',\n 'shelfBypassSecret',\n 'evalCohort',\n ...PUBLISH_CONFIG_KEYS,\n ...HOOKS_CONFIG_KEYS,\n ...LOOP_CONFIG_KEYS,\n ...TEAM_CONFIG_KEYS,\n]);\n\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...UPDATE_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS]\n .filter((key) => !SHELF_KEYS.has(key))\n .map((key) => key.length),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'automatic router limit per call',\n sessionBudget: 'automatic router daily limit: 0 blocks automatic spend, none removes the ceiling',\n sendMaxAmount:\n 'hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL the router asks',\n publicShelfUrl:\n 'the public marketplace, consume-only: the second shelf a team-mode search falls through to',\n shelfBypassSecret:\n \"the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)\",\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n bazaarRegistries: 'x402 registries used to verify direct-payment listings',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'publish.ackServerWarnings':\n \"whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never\",\n 'hooks.prompt': 'answer the prompt you just typed with what the shelves already know',\n 'hooks.web-search': 'ask Tenjin before the agent runs a WebSearch',\n 'hooks.web-fetch': 'ask Tenjin before the agent fetches a page',\n 'hooks.subagent':\n 'ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start',\n 'hooks.failure': 'answer a failing command with the fix this machine or a shelf already has',\n 'hooks.publish':\n 'the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end',\n 'hooks.primer': 'one-paragraph search-first primer at session start',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n 'loop.human_wait_ms':\n 'ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)',\n 'loop.tool_wait_ms': 'ms a hook fire may take when a tool call is waiting on it',\n 'loop.idle_exit_min': 'minutes without a hook fire before the loop daemon exits',\n 'loop.port':\n \"the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)\",\n 'team.publicFallback':\n 'on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)',\n 'router.enabled':\n 'false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it',\n 'router.context':\n 'session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled',\n 'experimental.bazaar':\n \"EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only\",\n};\n\n/**\n * What turning the experimental list on means, said when it is turned on:\n * whose services these are, that the price is theirs, and how to turn it off.\n */\nexport const EXPERIMENTAL_BAZAAR_WARNING =\n \"Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. \" +\n 'They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, ' +\n 'prices can vary with the input, and payments are real, under your spend limits. ' +\n \"To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. \" +\n \"Tenjin's reviewed list stays on either way. Turn this off with \" +\n '`tenjin config set experimental.bazaar off`.';\n\nfunction isExperimentalKey(key: string): key is ExperimentalConfigKey {\n return (EXPERIMENTAL_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isLoopKey(key: string): key is LoopConfigKey {\n return (LOOP_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isTeamKey(key: string): key is TeamConfigKey {\n return (TEAM_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isRouterKey(key: string): key is RouterConfigKey {\n return (ROUTER_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/** The list/get shape for a router key, with the file that set it. */\nfunction renderRouterSetting(key: RouterConfigKey, settings: RouterSettings): RenderedSetting {\n const { value, source, path } = key === 'router.enabled' ? settings.enabled : settings.context;\n return { value, source, ...(path !== undefined ? { path } : {}) };\n}\n\n/** Router keys resolve against the directory the command runs in, as a hook would. */\nasync function resolveRouterFromContext(ctx: CommandContext): Promise<RouterSettings> {\n return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });\n}\n\nfunction renderLoopSetting(key: LoopConfigKey, settings: EffectiveSettings): RenderedSetting {\n const field = key.slice('loop.'.length) as keyof EffectiveSettings['loop'];\n const { value, source } = settings.loop[field];\n return { value: value === null ? 'null' : String(value), source };\n}\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n const show = (key: string, line: string) => {\n if (!SHELF_KEYS.has(key)) humanLines.push(line);\n };\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of LOOP_CONFIG_KEYS) {\n const entry = renderLoopSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of TEAM_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.teamPublicFallback.value,\n source: settings.teamPublicFallback.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n const router = await resolveRouterFromContext(ctx);\n for (const key of ROUTER_CONFIG_KEYS) {\n const entry = renderRouterSetting(key, router);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of EXPERIMENTAL_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.experimentalBazaar.value,\n source: settings.experimentalBazaar.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isLoopKey(key)) {\n const entry = renderLoopSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isTeamKey(key)) {\n const { teamPublicFallback } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: teamPublicFallback.value,\n source: teamPublicFallback.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isRouterKey(key)) {\n const entry = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isExperimentalKey(key)) {\n const { experimentalBazaar } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: experimentalBazaar.value,\n source: experimentalBazaar.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n {\n key,\n value,\n project,\n local,\n }: { key: string; value: string; project?: boolean; local?: boolean },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (local === true && project !== true) {\n throw new CliError('USAGE', '--local names the personal project file, so it needs --project', {\n fix: `Run \\`tenjin config set --project --local ${key} ${value}\\`.`,\n });\n }\n if (isRouterKey(key)) {\n return setRouterKey(key, value, ctx, project === true ? { local: local === true } : undefined);\n }\n if (project === true) {\n throw new CliError('USAGE', `${key} is not a project key`, {\n fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(' and ')} only; drop it to set ${key} for this machine.`,\n });\n }\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n if (isLoopKey(key)) return setLoopKey(key, value, ctx);\n if (isTeamKey(key)) return setTeamKey(key, value, ctx);\n if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);\n return {\n data: { key: configKey, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(configKey, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * The half-wired team shelf, said out loud at the moment it is created.\n *\n * Team mode takes TWO settings — a private deployment in `baseUrl` and its\n * bypass secret — and the setup is two independent commands, so a machine can\n * easily end up with the secret and no shelf (run in the other order, or the\n * secret line alone on a second machine). The CLI fails that state safe to\n * public mode, which means an operator who thinks they are on the team shelf\n * would otherwise get no signal at all: publishes would go to the marketplace\n * under the public gates. Warn, do not refuse — the pair is legitimately\n * half-set between two commands, and refusing would make the documented order\n * the only order.\n *\n * THREE KEYS, not two. `isTeamShelfOrigin` also returns false when `baseUrl`\n * matches `publicShelfUrl`, so pointing `publicShelfUrl` at the team deployment\n * drops the machine out of team mode just as surely as unsetting the secret\n * would. It fails safe and doctor catches it later; this is the warning at the\n * moment it happens, on the third key of the same triple.\n */\nasync function halfWiredTeamShelf(\n configKey: ScalarConfigKey,\n dataDir: string,\n): Promise<string | undefined> {\n if (\n configKey !== 'shelfBypassSecret' &&\n configKey !== 'baseUrl' &&\n configKey !== 'publicShelfUrl'\n ) {\n return undefined;\n }\n const config = await loadRawConfig(dataDir).catch(() => undefined);\n if (config === undefined) return undefined;\n const s = resolveSettings({ config, flags: {}, env: {} });\n if (s.shelfBypassSecret.value.length === 0) return undefined;\n const baseUrl = s.baseUrl.value;\n if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return undefined;\n // WHICH KEY BROKE THE PAIR decides which fix to name. A baseUrl that now\n // matches publicShelfUrl is not \"the marketplace\" in any recognizable sense —\n // it is the operator's own two keys pointed at one place — and telling them to\n // re-point baseUrl would be advice for the other half of the same collision.\n const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);\n const cause = isProduction\n ? `baseUrl is the public marketplace (${baseUrl})`\n : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;\n const fix = isProduction\n ? 'Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`.'\n : `A team shelf must differ from the shelf it falls through to: \\`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\\`.`;\n return (\n `Warning: shelfBypassSecret is set, but ${cause}, ` +\n 'so this machine stays in PUBLIC mode — publishes go to the marketplace with the scan’s ' +\n 'warn tier and the confirm cascade on. ' +\n fix\n );\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice|publish.ackServerWarnings`. mode\n * and ackServerWarnings validate to their enums; defaultPrice parses decimal USD\n * at the edge into atomic (matching the spend keys). The subkey is merged into\n * the nested publish block, so a sibling subkey (or an unknown one a newer CLI\n * wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : key === 'publish.ackServerWarnings'\n ? { value: parseAckServerWarnings(value, key), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey =\n key === 'publish.mode'\n ? 'mode'\n : key === 'publish.ackServerWarnings'\n ? 'ackServerWarnings'\n : 'defaultPrice';\n const stored =\n key === 'publish.defaultPrice' ? (entry.value as Money).atomic : (entry.value as string);\n const persistEntry = async (): Promise<void> =>\n persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') {\n await persistEntry();\n return { data: { key, ...entry }, humanLines };\n }\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n // Synchronize before committing the mode. A grant writer may refuse after\n // consent (permissions, concurrent edits, an unwritable parent); persisting\n // first made the command exit successfully with an unattended mode that its\n // harness could not carry. Grant-first is also the least-authority failure\n // order: if a later config write fails, the CLI still resolves the old mode.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n const failure = grantSyncFailure(allowlist);\n if (failure !== undefined) {\n throw new CliError(\n 'REFUSED',\n `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,\n {\n fix:\n failure.fix ??\n `Fix the permissions for ${failure.path}, then re-run \\`tenjin config set publish.mode ${entry.value as string}\\`.`,\n details: { key, value: entry.value, allowlist },\n },\n );\n }\n await persistEntry();\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n byHarness: Partial<Record<Harness, PermissionsResult | CodexGrantResult>>;\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** A writer refusal is an error, not informational output: the mode and every\n * harness grant are one operator decision and may not report success apart. */\nfunction grantSyncFailure(\n sync: AllowlistSync,\n): { harness: Harness; path: string; reason: string; fix?: string } | undefined {\n for (const [harness, result] of Object.entries(sync.byHarness) as [\n Harness,\n PermissionsResult | CodexGrantResult,\n ][]) {\n if ('error' in result && result.error !== undefined) {\n return { harness, path: result.path, reason: result.error };\n }\n if ('warning' in result && result.warning !== undefined) {\n return {\n harness,\n path: result.path ?? '(unknown path)',\n reason: result.warning,\n ...(result.fix !== undefined ? { fix: result.fix } : {}),\n };\n }\n }\n return undefined;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(\n mode: PublishMode,\n pending: readonly string[],\n harnesses: readonly Harness[],\n): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} command-grant rule(s) \\`tenjin install\\` writes.` : '';\n const targets = harnesses\n .map((harness) =>\n harness === 'claude' ? 'Claude Code' : harness === 'codex' ? 'Codex' : harness,\n )\n .join(' and ');\n return (\n `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ` +\n `${MODE_GATED_RULES.join(' and ')}. Update the ${targets} grant now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { byHarness: {} };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n byHarness: { claude: result },\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { byHarness: { claude: result } };\n };\n\n const adapters = deps.adapters ?? ADAPTERS;\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((config) => config.install?.harness ?? [])\n .catch(() => [] as Harness[]);\n const inPlay =\n deps.harnessesInPlay ??\n (\n await Promise.all(\n Object.values(adapters).map(async (adapter) => ({\n adapter,\n selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {\n env,\n which,\n requested,\n }),\n })),\n )\n )\n .filter((entry) => entry.selected)\n .map((entry) => entry.adapter.id);\n const selectedAdapters = inPlay.map((harness) => adapters[harness]);\n const isClaude = inPlay.includes('claude');\n\n const withOtherGrants = async (sync: AllowlistSync): Promise<AllowlistSync> => {\n const byHarness = { ...sync.byHarness };\n for (const adapter of selectedAdapters) {\n if (adapter.id === 'claude' || adapter.registrar.grant === undefined) continue;\n const result = await adapter.registrar.grant.write(home, mode, env);\n byHarness[adapter.id] = result;\n }\n return { ...sync, byHarness };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n if (selectedAdapters.every((adapter) => adapter.registrar.grant === undefined)) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = isClaude\n ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode)\n : { pending: [] as string[] };\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = isClaude\n ? await (deps.retractModeGated ?? retractModeGatedRules)(home)\n : undefined;\n if (retracted?.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return await withOtherGrants({\n byHarness: retracted === undefined ? {} : { claude: retracted },\n });\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined && selectedAdapters.length === 1 && isClaude) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) {\n return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n }\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n const grantable = selectedAdapters\n .filter((adapter) => adapter.registrar.grant !== undefined)\n .map((adapter) => adapter.id);\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable)))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return await withOtherGrants(isClaude ? await write() : nothing);\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n const claude = sync.byHarness.claude as PermissionsResult | undefined;\n if ((claude?.added.length ?? 0) > 0) {\n lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);\n }\n if ((claude?.removed.length ?? 0) > 0) {\n lines.push(`Removed ${claude?.removed.join(', ')} from your allowlist.`);\n }\n const grant = sync.byHarness.codex as CodexGrantResult | undefined;\n if (grant !== undefined && grant.error === undefined && grant.wrote) {\n lines.push(\n `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`,\n );\n }\n if (grant?.error !== undefined) {\n lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.<arm>`. Merged into the nested hooks block through the same\n * locked read-modify-write every other set uses, so a subkey a newer CLI wrote\n * survives. The daemon re-stats this file per fire, so every value takes effect\n * on the next prompt with no re-install and no process to restart.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const arm = key.slice('hooks.'.length) as HookArm;\n const parsed = parseBoolean(value);\n await persistHookArm(ctx.dataDir, arm, parsed);\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // NO STALENESS WARNING, and there is nothing left to warn about: every hooks\n // key is read out of `config.json` by the daemon on each fire, so a value set\n // here takes effect on the next prompt with nothing to re-install.\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set loop.*` and `config set team.publicFallback`. The daemon stats\n * `config.json` per fire and reloads on an mtime change, so a set takes effect\n * on the next hook fire with no restart (02-redesign.md §4a).\n */\nasync function setLoopKey(\n key: LoopConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseLoopValue(key, value);\n const field = key.slice('loop.'.length);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n loop: { ...existing.loop, [field]: parsed },\n }));\n const entry: RenderedSetting = {\n value: parsed === null ? 'null' : String(parsed),\n source: 'file',\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nasync function setTeamKey(\n key: TeamConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n team: { ...existing.team, publicFallback: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/** `config set experimental.bazaar on|off`; turning it on says what it means. */\nasync function setExperimentalKey(\n key: ExperimentalConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n experimental: { ...existing.experimental, bazaar: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n const warning = parsed === 'on' ? EXPERIMENTAL_BAZAAR_WARNING : undefined;\n return {\n data: { key, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(key, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * `config set [--project [--local]] router.enabled|router.context`. Without\n * `--project` the key goes into the global config through the same locked merge\n * every set uses. With it, into the project file {@link projectRouterPath}\n * names from here, merged so a sibling key survives. The line after the write\n * is what a hook here would now resolve, which differs from the value written\n * when an outer layer is tighter.\n */\nasync function setRouterKey(\n key: RouterConfigKey,\n value: string,\n ctx: CommandContext,\n project: { local: boolean } | undefined,\n): Promise<CommandResult> {\n const field = key === 'router.enabled' ? 'enabled' : 'context';\n const parsed = field === 'enabled' ? parseBoolean(value) : parseRouterContext(value);\n let written: RenderedSetting;\n if (project === undefined) {\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n router: { ...existing.router, [field]: parsed },\n }));\n written = { value: parsed, source: 'file', path: configPath(ctx.dataDir) };\n } else {\n const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });\n await persistProjectRouter(path, field, parsed);\n written = { value: parsed, source: project.local ? 'local' : 'project', path };\n }\n const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n const humanLines = [formatLine(key, written)];\n if (effective.value !== written.value) {\n humanLines.push(\n `Still ${String(effective.value)} here: ${effective.path ?? 'the default'} is tighter, and a nearer file can only tighten an outer one.`,\n );\n }\n if (project?.local === true) {\n humanLines.push('Keep .tenjin/config.local.json out of git: add it to .gitignore.');\n }\n return { data: { key, ...written, effective }, humanLines };\n}\n\nfunction parseRouterContext(value: string): RouterContext {\n const found = ROUTER_CONTEXTS.find((context) => context === value);\n if (found !== undefined) return found;\n throw new CliError('USAGE', `Invalid router.context: ${JSON.stringify(value)}`, {\n fix: 'Use \"session\" or \"turn\".',\n });\n}\n\n/**\n * Merge one router key into a project file. It holds the router block and\n * nothing else this CLI reads, so it is written 0644 like any committed file;\n * an existing file that is not a JSON object is refused rather than replaced.\n * The read, merge and write run under the same cross-process lock the global\n * writer takes, so two concurrent sets both land.\n */\nasync function persistProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o755 });\n const lockPath = `${path}.lock`;\n try {\n await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));\n } catch (err) {\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nasync function mergeProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n // Through the one parser: a file that is not an object, or whose block is\n // invalid, is refused rather than replaced. A router subkey this build does\n // not know rides along untouched, as in the global file; it is never read.\n const existing = await readProjectRouterFile(path);\n const block = existing?.json.router;\n const next = {\n ...(existing?.json ?? {}),\n router: { ...(block !== undefined ? (block as object) : {}), [field]: value },\n };\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o755,\n });\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The one writer of a `hooks.<arm>` boolean, through the same locked merge-write\n * every `config set` uses, so a sibling arm or an unknown block a newer CLI\n * wrote survives. `config set hooks.<arm>` and `tenjin hooks enable|disable`\n * are two spellings of this call and never two writers.\n */\nexport async function persistHookArm(dir: string, arm: HookArm, value: boolean): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [arm]: value },\n }));\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Remember, or forget, a project directory this machine wired with\n * `install --project`. `tenjin update` spawns its refresh from the HOME\n * directory, so a project install is unfindable by looking around; this list is\n * how a later refresh reaches it. Absolute paths, de-duplicated, and pruned\n * when a project is uninstalled or its settings file stops carrying our\n * entries.\n */\nexport async function persistRouterProject(\n dir: string,\n projectDir: string,\n present = true,\n): Promise<void> {\n await persist(dir, (existing) => {\n const known = new Set(existing.install?.routerProjects ?? []);\n if (present) known.add(projectDir);\n else known.delete(projectDir);\n return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };\n });\n}\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\nexport interface RouterDefaultsResult {\n /** Keys this run wrote, because the file did not name them. */\n set: string[];\n /** Keys the operator had already written, left exactly as they are. */\n kept: string[];\n removed: string[];\n}\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** Remove/report retired keys in the same locked write. Refresh preserves absent\n * current settings; a fresh install fills only missing automatic limits, with the\n * values the person at the terminal approved or chose. */\nexport async function persistRouterDefaults(\n dir: string,\n refresh = false,\n limits: RouterLimits = ROUTER_DEFAULTS,\n): Promise<RouterDefaultsResult> {\n const result: RouterDefaultsResult = { set: [], kept: [], removed: [] };\n if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;\n await persist(dir, (existing) => {\n const next: PartialConfig = { ...existing };\n result.removed = retiredPaymentKeys(existing);\n for (const key of result.removed) delete next[key];\n if (refresh) return next;\n for (const [key, value] of Object.entries(limits) as [keyof RouterLimits, string][]) {\n if (existing[key] === undefined) {\n next[key] = value;\n result.set.push(key);\n } else result.kept.push(key);\n }\n return next;\n });\n return result;\n}\n\n/**\n * Record the settled harness selection through the same locked merge-write. It\n * replaces the previous record rather than unioning with it: the last operator\n * answer is the current intent. Doctor still re-probes detection independently;\n * the record keeps a deliberately selected but currently undetected harness in play.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly Harness[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\n/**\n * Record the EXACT free-verb rules `install` declined, through the same locked\n * read-modify-write every `config set` uses. Set to whatever was pending at the\n * moment of `--no-grant`; cleared back to `[]` the moment an install\n * actually wires the allowlist, or finds it already fully satisfied. `--refresh` subtracts this list from what it would otherwise\n * report as pending, so a settled no stays settled per rule — without also\n * silencing a genuinely NEW rule a later version adds (tenjin-agent#234).\n */\nexport async function persistGrantDeclined(dir: string, declined: string[]): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, grantDeclined: declined },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if (key === 'bazaarPay' || key === 'confirm') {\n throw new CliError('USAGE', `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });\n }\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n if (key === 'publish.ackServerWarnings') {\n return {\n value: settings.publishAckServerWarnings.value,\n source: settings.publishAckServerWarnings.source,\n };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: the arm's boolean and where it came from. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const { value, source } = settings.hooks[key.slice('hooks.'.length) as HookArm];\n return { value, source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n // REDACTED IN THE MACHINE ENVELOPE TOO, not just in the human line. `config\n // --json` is what an agent reads and what a bug report pastes, and the whole\n // point of a door key is that it opens the door for whoever holds it. What a\n // caller actually needs from this key is whether team mode is on, and\n // set/unset says exactly that. The value is still readable, by the operator,\n // in ~/.tenjin/config.json.\n if (key === 'shelfBypassSecret') {\n return { value: typeof stored === 'string' && stored.length > 0 ? 'set' : 'unset' };\n }\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'sessionBudget' && stored === 'none') return { value: null };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'sessionBudget':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'maxAutoSpend':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'publicShelfUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'shelfBypassSecret':\n // A free string: it is whatever Vercel generated. Empty clears it, which\n // is how team mode is turned back off.\n return value.trim();\n case 'evalCohort':\n return parseBoolean(value);\n case 'bazaarRegistries':\n return parseRegistryList(value);\n }\n}\n\n/** \"\" clears to []; comma-split, each entry an absolute http(s) URL. */\nfunction parseRegistryList(value: string): string[] {\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n .map((entry) => parseHttpUrl(entry));\n}\n\n// Boolean settings accept both on/off and true/false.\nfunction parseBoolean(value: string): boolean {\n if (value === 'true' || value === 'on') return true;\n if (value === 'false' || value === 'off') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\" (or \"true\"/\"false\").',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n // 0600, matching lib/config.ts's `writeConfig`: this file holds\n // `shelfBypassSecret`, and this is the writer `config set` uses to put it\n // there. See that function for why dirMode alone is not enough.\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n // A router key from a project names its file: which of several is in force is the question.\n const where =\n entry.path !== undefined && (entry.source === 'project' || entry.source === 'local')\n ? ` ${entry.path}`\n : '';\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source}${where})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (value === null) return 'none (no daily limit)';\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n return value; // 'always', baseUrl, rpcUrl\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\nexport const RETIRED_SKILL_NAMES = ['tenjin-pay'] as const;\n\n/** Retired names remain known to uninstall, but are never packaged or healed. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n */\nexport const SHIPPED_SKILL_FILES: Record<\n SkillName | (typeof RETIRED_SKILL_NAMES)[number],\n readonly string[]\n> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import type { Harness, HarnessAdapter } from '../adapters/types';\nimport { registeredHooks } from './harness-hooks';\nimport { detectHarnesses, harnessInPlay, harnessTargetDir, onPath } from './skill-wiring';\n\n/**\n * Is one adapter part of this machine's settled installation?\n *\n * An explicit install selection outranks current detection; homes predating\n * that record fall back to the harness directory/PATH probes. Registered hook\n * entries are final evidence, so config and doctor agree even if the binary or\n * home-directory marker later moves.\n */\nexport async function installedHarnessInPlay(\n adapter: HarnessAdapter,\n home: string,\n dataDir: string,\n options: {\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n requested?: readonly Harness[];\n } = {},\n): Promise<boolean> {\n const env = options.env ?? process.env;\n const which = options.which ?? ((bin: string) => onPath(bin, env));\n if (\n harnessInPlay(\n home,\n harnessTargetDir(home, adapter.id),\n detectHarnesses(home, which),\n options.requested ?? [],\n )\n ) {\n return true;\n }\n return (await registeredHooks(adapter, home, dataDir, env)).entries > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,WAAAA,gBAAe;AACxB,SAAS,iBAAiB;;;ACH1B,SAAS,YAAY,gBAAgB;AACrC,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,QAC1C,KAAK,iDAAiD,QAAQ;AAAA,QAC9D,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AACA,UAAM;AAAA,EACR;AACF;AAEA,SAAS,WAAW,KAAa,OAAgC;AAC/D,QAAM,QAAQ,IAAI,OAAO,SAAS;AAElC,QAAM,QACJ,MAAM,SAAS,WAAc,MAAM,WAAW,aAAa,MAAM,WAAW,WACxE,IAAI,MAAM,IAAI,KACd;AACN,SAAO,KAAK,KAAK,KAAK,aAAa,KAAK,CAAC,KAAK,UAAU,OAAO,IAAI,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC;AAC7F;AAGA,SAAS,cAAc,KAAa,OAAwB,MAAuB;AACjF,QAAM,cAAc,iBAAiB,GAAG;AACxC,MAAI,OAAO,WAAW,KAAK,KAAK;AAChC,MAAI,gBAAgB,OAAW,SAAQ,KAAK,UAAU,OAAO,KAAK,WAAW,EAAE,CAAC;AAChF,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,UAAU,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AAC5E;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,SAAO;AACT;","names":["dirname","join","join","open","settings","entry","dirname"]}
1
+ {"version":3,"sources":["../src/commands/config.ts","../src/lib/skill-wiring.ts","../src/lib/skills-source.ts","../src/lib/harness-presence.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname } from 'node:path';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport type { CodexGrantResult } from '../lib/harness-permissions';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from '../lib/production-origin';\nimport {\n CONFIG_KEYS,\n RETIRED_PAYMENT_GUIDANCE,\n retiredPaymentKeys,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n LOOP_CONFIG_KEYS,\n TEAM_CONFIG_KEYS,\n EXPERIMENTAL_CONFIG_KEYS,\n ROUTER_CONFIG_KEYS,\n ROUTER_CONTEXTS,\n loadRawConfig,\n parseLoopValue,\n parsePublicFallbackFlag,\n parseAckServerWarnings,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HookArm,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n UpdateConfigKey,\n LoopConfigKey,\n TeamConfigKey,\n ExperimentalConfigKey,\n RouterConfigKey,\n RouterContext,\n} from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { Harness, HarnessAdapter } from '../adapters/types';\nimport { ADAPTERS } from '../adapters/registry';\nimport { isTeamShelfOrigin, loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { installedHarnessInPlay } from '../lib/harness-presence';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\nimport {\n projectRouterPath,\n readProjectRouterFile,\n routerSettings,\n type RouterSettings,\n} from '../router/settings';\n\n/** Machine values use Money for spending keys and scalars for other settings. */\ninterface RenderedValue {\n value: Money | string | string[] | boolean | null;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n /** The file a router key came from, when one did. */\n path?: string;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Harness lifecycle implementations; tests inject adapters at this boundary. */\n adapters?: Readonly<Record<Harness, HarnessAdapter>>;\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Settled harness selection; absent, each registered adapter is detected normally. */\n harnessesInPlay?: readonly Harness[];\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\n/**\n * The shelf's settings. `config get/set` still accept them and `--json` still\n * carries them, but the human listing shows only what the router CLI uses: it\n * ships no shelf command that reads these.\n */\nconst SHELF_KEYS: ReadonlySet<string> = new Set<string>([\n 'allowlistCreators',\n 'publicShelfUrl',\n 'shelfBypassSecret',\n 'evalCohort',\n ...PUBLISH_CONFIG_KEYS,\n ...HOOKS_CONFIG_KEYS,\n ...LOOP_CONFIG_KEYS,\n ...TEAM_CONFIG_KEYS,\n]);\n\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...UPDATE_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS]\n .filter((key) => !SHELF_KEYS.has(key))\n .map((key) => key.length),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'automatic router limit per call',\n sessionBudget: 'automatic router daily limit: 0 blocks automatic spend, none removes the ceiling',\n sendMaxAmount:\n 'hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL the router asks',\n publicShelfUrl:\n 'the public marketplace, consume-only: the second shelf a team-mode search falls through to',\n shelfBypassSecret:\n \"the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)\",\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n bazaarRegistries: 'x402 registries used to verify direct-payment listings',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'publish.ackServerWarnings':\n \"whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never\",\n 'hooks.prompt': 'answer the prompt you just typed with what the shelves already know',\n 'hooks.web-search': 'ask Tenjin before the agent runs a WebSearch',\n 'hooks.web-fetch': 'ask Tenjin before the agent fetches a page',\n 'hooks.subagent':\n 'ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start',\n 'hooks.failure': 'answer a failing command with the fix this machine or a shelf already has',\n 'hooks.publish':\n 'the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end',\n 'hooks.primer': 'one-paragraph search-first primer at session start',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n 'loop.human_wait_ms':\n 'ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)',\n 'loop.tool_wait_ms': 'ms a hook fire may take when a tool call is waiting on it',\n 'loop.idle_exit_min': 'minutes without a hook fire before the loop daemon exits',\n 'loop.port':\n \"the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)\",\n 'team.publicFallback':\n 'on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)',\n 'router.enabled':\n 'false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it',\n 'router.context':\n 'session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled',\n 'experimental.bazaar':\n \"EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only\",\n};\n\n/**\n * What turning the experimental list on means, said when it is turned on:\n * whose services these are, that the price is theirs, and how to turn it off.\n */\nexport const EXPERIMENTAL_BAZAAR_WARNING =\n \"Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. \" +\n 'They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, ' +\n 'prices can vary with the input, and payments are real, under your spend limits. ' +\n \"To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. \" +\n \"Tenjin's reviewed list stays on either way. Turn this off with \" +\n '`tenjin config set experimental.bazaar off`.';\n\nfunction isExperimentalKey(key: string): key is ExperimentalConfigKey {\n return (EXPERIMENTAL_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isLoopKey(key: string): key is LoopConfigKey {\n return (LOOP_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isTeamKey(key: string): key is TeamConfigKey {\n return (TEAM_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isRouterKey(key: string): key is RouterConfigKey {\n return (ROUTER_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/** The list/get shape for a router key, with the file that set it. */\nfunction renderRouterSetting(key: RouterConfigKey, settings: RouterSettings): RenderedSetting {\n const { value, source, path } = key === 'router.enabled' ? settings.enabled : settings.context;\n return { value, source, ...(path !== undefined ? { path } : {}) };\n}\n\n/** Router keys resolve against the directory the command runs in, as a hook would. */\nasync function resolveRouterFromContext(ctx: CommandContext): Promise<RouterSettings> {\n return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });\n}\n\nfunction renderLoopSetting(key: LoopConfigKey, settings: EffectiveSettings): RenderedSetting {\n const field = key.slice('loop.'.length) as keyof EffectiveSettings['loop'];\n const { value, source } = settings.loop[field];\n return { value: value === null ? 'null' : String(value), source };\n}\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n const show = (key: string, line: string) => {\n if (!SHELF_KEYS.has(key)) humanLines.push(line);\n };\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of LOOP_CONFIG_KEYS) {\n const entry = renderLoopSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of TEAM_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.teamPublicFallback.value,\n source: settings.teamPublicFallback.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n const router = await resolveRouterFromContext(ctx);\n for (const key of ROUTER_CONFIG_KEYS) {\n const entry = renderRouterSetting(key, router);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of EXPERIMENTAL_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.experimentalBazaar.value,\n source: settings.experimentalBazaar.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isLoopKey(key)) {\n const entry = renderLoopSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isTeamKey(key)) {\n const { teamPublicFallback } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: teamPublicFallback.value,\n source: teamPublicFallback.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isRouterKey(key)) {\n const entry = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isExperimentalKey(key)) {\n const { experimentalBazaar } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: experimentalBazaar.value,\n source: experimentalBazaar.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n {\n key,\n value,\n project,\n local,\n }: { key: string; value: string; project?: boolean; local?: boolean },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (local === true && project !== true) {\n throw new CliError('USAGE', '--local names the personal project file, so it needs --project', {\n fix: `Run \\`tenjin config set --project --local ${key} ${value}\\`.`,\n });\n }\n if (isRouterKey(key)) {\n return setRouterKey(key, value, ctx, project === true ? { local: local === true } : undefined);\n }\n if (project === true) {\n throw new CliError('USAGE', `${key} is not a project key`, {\n fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(' and ')} only; drop it to set ${key} for this machine.`,\n });\n }\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n if (isLoopKey(key)) return setLoopKey(key, value, ctx);\n if (isTeamKey(key)) return setTeamKey(key, value, ctx);\n if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);\n return {\n data: { key: configKey, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(configKey, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * The half-wired team shelf, said out loud at the moment it is created.\n *\n * Team mode takes TWO settings — a private deployment in `baseUrl` and its\n * bypass secret — and the setup is two independent commands, so a machine can\n * easily end up with the secret and no shelf (run in the other order, or the\n * secret line alone on a second machine). The CLI fails that state safe to\n * public mode, which means an operator who thinks they are on the team shelf\n * would otherwise get no signal at all: publishes would go to the marketplace\n * under the public gates. Warn, do not refuse — the pair is legitimately\n * half-set between two commands, and refusing would make the documented order\n * the only order.\n *\n * THREE KEYS, not two. `isTeamShelfOrigin` also returns false when `baseUrl`\n * matches `publicShelfUrl`, so pointing `publicShelfUrl` at the team deployment\n * drops the machine out of team mode just as surely as unsetting the secret\n * would. It fails safe and doctor catches it later; this is the warning at the\n * moment it happens, on the third key of the same triple.\n */\nasync function halfWiredTeamShelf(\n configKey: ScalarConfigKey,\n dataDir: string,\n): Promise<string | undefined> {\n if (\n configKey !== 'shelfBypassSecret' &&\n configKey !== 'baseUrl' &&\n configKey !== 'publicShelfUrl'\n ) {\n return undefined;\n }\n const config = await loadRawConfig(dataDir).catch(() => undefined);\n if (config === undefined) return undefined;\n const s = resolveSettings({ config, flags: {}, env: {} });\n if (s.shelfBypassSecret.value.length === 0) return undefined;\n const baseUrl = s.baseUrl.value;\n if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return undefined;\n // WHICH KEY BROKE THE PAIR decides which fix to name. A baseUrl that now\n // matches publicShelfUrl is not \"the marketplace\" in any recognizable sense —\n // it is the operator's own two keys pointed at one place — and telling them to\n // re-point baseUrl would be advice for the other half of the same collision.\n const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);\n const cause = isProduction\n ? `baseUrl is the public marketplace (${baseUrl})`\n : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;\n const fix = isProduction\n ? 'Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`.'\n : `A team shelf must differ from the shelf it falls through to: \\`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\\`.`;\n return (\n `Warning: shelfBypassSecret is set, but ${cause}, ` +\n 'so this machine stays in PUBLIC mode — publishes go to the marketplace with the scan’s ' +\n 'warn tier and the confirm cascade on. ' +\n fix\n );\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice|publish.ackServerWarnings`. mode\n * and ackServerWarnings validate to their enums; defaultPrice parses decimal USD\n * at the edge into atomic (matching the spend keys). The subkey is merged into\n * the nested publish block, so a sibling subkey (or an unknown one a newer CLI\n * wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : key === 'publish.ackServerWarnings'\n ? { value: parseAckServerWarnings(value, key), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey =\n key === 'publish.mode'\n ? 'mode'\n : key === 'publish.ackServerWarnings'\n ? 'ackServerWarnings'\n : 'defaultPrice';\n const stored =\n key === 'publish.defaultPrice' ? (entry.value as Money).atomic : (entry.value as string);\n const persistEntry = async (): Promise<void> =>\n persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') {\n await persistEntry();\n return { data: { key, ...entry }, humanLines };\n }\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n // Synchronize before committing the mode. A grant writer may refuse after\n // consent (permissions, concurrent edits, an unwritable parent); persisting\n // first made the command exit successfully with an unattended mode that its\n // harness could not carry. Grant-first is also the least-authority failure\n // order: if a later config write fails, the CLI still resolves the old mode.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n const failure = grantSyncFailure(allowlist);\n if (failure !== undefined) {\n throw new CliError(\n 'REFUSED',\n `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,\n {\n fix:\n failure.fix ??\n `Fix the permissions for ${failure.path}, then re-run \\`tenjin config set publish.mode ${entry.value as string}\\`.`,\n details: { key, value: entry.value, allowlist },\n },\n );\n }\n await persistEntry();\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n byHarness: Partial<Record<Harness, PermissionsResult | CodexGrantResult>>;\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** A writer refusal is an error, not informational output: the mode and every\n * harness grant are one operator decision and may not report success apart. */\nfunction grantSyncFailure(\n sync: AllowlistSync,\n): { harness: Harness; path: string; reason: string; fix?: string } | undefined {\n for (const [harness, result] of Object.entries(sync.byHarness) as [\n Harness,\n PermissionsResult | CodexGrantResult,\n ][]) {\n if ('error' in result && result.error !== undefined) {\n return { harness, path: result.path, reason: result.error };\n }\n if ('warning' in result && result.warning !== undefined) {\n return {\n harness,\n path: result.path ?? '(unknown path)',\n reason: result.warning,\n ...(result.fix !== undefined ? { fix: result.fix } : {}),\n };\n }\n }\n return undefined;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(\n mode: PublishMode,\n pending: readonly string[],\n harnesses: readonly Harness[],\n): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} command-grant rule(s) \\`tenjin install\\` writes.` : '';\n const targets = harnesses\n .map((harness) =>\n harness === 'claude' ? 'Claude Code' : harness === 'codex' ? 'Codex' : harness,\n )\n .join(' and ');\n return (\n `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ` +\n `${MODE_GATED_RULES.join(' and ')}. Update the ${targets} grant now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { byHarness: {} };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n byHarness: { claude: result },\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { byHarness: { claude: result } };\n };\n\n const adapters = deps.adapters ?? ADAPTERS;\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((config) => config.install?.harness ?? [])\n .catch(() => [] as Harness[]);\n const inPlay =\n deps.harnessesInPlay ??\n (\n await Promise.all(\n Object.values(adapters).map(async (adapter) => ({\n adapter,\n selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {\n env,\n which,\n requested,\n }),\n })),\n )\n )\n .filter((entry) => entry.selected)\n .map((entry) => entry.adapter.id);\n const selectedAdapters = inPlay.map((harness) => adapters[harness]);\n const isClaude = inPlay.includes('claude');\n\n const withOtherGrants = async (sync: AllowlistSync): Promise<AllowlistSync> => {\n const byHarness = { ...sync.byHarness };\n for (const adapter of selectedAdapters) {\n if (adapter.id === 'claude' || adapter.registrar.grant === undefined) continue;\n const result = await adapter.registrar.grant.write(home, mode, env);\n byHarness[adapter.id] = result;\n }\n return { ...sync, byHarness };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n if (selectedAdapters.every((adapter) => adapter.registrar.grant === undefined)) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = isClaude\n ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode)\n : { pending: [] as string[] };\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = isClaude\n ? await (deps.retractModeGated ?? retractModeGatedRules)(home)\n : undefined;\n if (retracted?.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return await withOtherGrants({\n byHarness: retracted === undefined ? {} : { claude: retracted },\n });\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined && selectedAdapters.length === 1 && isClaude) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) {\n return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n }\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n const grantable = selectedAdapters\n .filter((adapter) => adapter.registrar.grant !== undefined)\n .map((adapter) => adapter.id);\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable)))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return await withOtherGrants(isClaude ? await write() : nothing);\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n const claude = sync.byHarness.claude as PermissionsResult | undefined;\n if ((claude?.added.length ?? 0) > 0) {\n lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);\n }\n if ((claude?.removed.length ?? 0) > 0) {\n lines.push(`Removed ${claude?.removed.join(', ')} from your allowlist.`);\n }\n const grant = sync.byHarness.codex as CodexGrantResult | undefined;\n if (grant !== undefined && grant.error === undefined && grant.wrote) {\n lines.push(\n `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`,\n );\n }\n if (grant?.error !== undefined) {\n lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.<arm>`. Merged into the nested hooks block through the same\n * locked read-modify-write every other set uses, so a subkey a newer CLI wrote\n * survives. The daemon re-stats this file per fire, so every value takes effect\n * on the next prompt with no re-install and no process to restart.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const arm = key.slice('hooks.'.length) as HookArm;\n const parsed = parseBoolean(value);\n await persistHookArm(ctx.dataDir, arm, parsed);\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // NO STALENESS WARNING, and there is nothing left to warn about: every hooks\n // key is read out of `config.json` by the daemon on each fire, so a value set\n // here takes effect on the next prompt with nothing to re-install.\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set loop.*` and `config set team.publicFallback`. The daemon stats\n * `config.json` per fire and reloads on an mtime change, so a set takes effect\n * on the next hook fire with no restart (02-redesign.md §4a).\n */\nasync function setLoopKey(\n key: LoopConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseLoopValue(key, value);\n const field = key.slice('loop.'.length);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n loop: { ...existing.loop, [field]: parsed },\n }));\n const entry: RenderedSetting = {\n value: parsed === null ? 'null' : String(parsed),\n source: 'file',\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nasync function setTeamKey(\n key: TeamConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n team: { ...existing.team, publicFallback: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/** `config set experimental.bazaar on|off`; turning it on says what it means. */\nasync function setExperimentalKey(\n key: ExperimentalConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n experimental: { ...existing.experimental, bazaar: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n const warning = parsed === 'on' ? EXPERIMENTAL_BAZAAR_WARNING : undefined;\n return {\n data: { key, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(key, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * `config set [--project [--local]] router.enabled|router.context`. Without\n * `--project` the key goes into the global config through the same locked merge\n * every set uses. With it, into the project file {@link projectRouterPath}\n * names from here, merged so a sibling key survives. The line after the write\n * is what a hook here would now resolve, which differs from the value written\n * when an outer layer is tighter.\n */\nasync function setRouterKey(\n key: RouterConfigKey,\n value: string,\n ctx: CommandContext,\n project: { local: boolean } | undefined,\n): Promise<CommandResult> {\n const field = key === 'router.enabled' ? 'enabled' : 'context';\n const parsed = field === 'enabled' ? parseBoolean(value) : parseRouterContext(value);\n let written: RenderedSetting;\n if (project === undefined) {\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n router: { ...existing.router, [field]: parsed },\n }));\n written = { value: parsed, source: 'file', path: configPath(ctx.dataDir) };\n } else {\n const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });\n await persistProjectRouter(path, field, parsed);\n written = { value: parsed, source: project.local ? 'local' : 'project', path };\n }\n const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n const humanLines = [formatLine(key, written)];\n if (effective.value !== written.value) {\n humanLines.push(\n `Still ${String(effective.value)} here: ${effective.path ?? 'the default'} is tighter, and a nearer file can only tighten an outer one.`,\n );\n }\n if (project?.local === true) {\n humanLines.push('Keep .tenjin/config.local.json out of git: add it to .gitignore.');\n }\n return { data: { key, ...written, effective }, humanLines };\n}\n\nfunction parseRouterContext(value: string): RouterContext {\n const found = ROUTER_CONTEXTS.find((context) => context === value);\n if (found !== undefined) return found;\n throw new CliError('USAGE', `Invalid router.context: ${JSON.stringify(value)}`, {\n fix: 'Use \"session\" or \"turn\".',\n });\n}\n\n/**\n * Merge one router key into a project file. It holds the router block and\n * nothing else this CLI reads, so it is written 0644 like any committed file;\n * an existing file that is not a JSON object is refused rather than replaced.\n * The read, merge and write run under the same cross-process lock the global\n * writer takes, so two concurrent sets both land.\n */\nasync function persistProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o755 });\n const lockPath = `${path}.lock`;\n try {\n await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));\n } catch (err) {\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nasync function mergeProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n // Through the one parser: a file that is not an object, or whose block is\n // invalid, is refused rather than replaced. A router subkey this build does\n // not know rides along untouched, as in the global file; it is never read.\n const existing = await readProjectRouterFile(path);\n const block = existing?.json.router;\n const next = {\n ...(existing?.json ?? {}),\n router: { ...(block !== undefined ? (block as object) : {}), [field]: value },\n };\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o755,\n });\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The one writer of a `hooks.<arm>` boolean, through the same locked merge-write\n * every `config set` uses, so a sibling arm or an unknown block a newer CLI\n * wrote survives. `config set hooks.<arm>` and `tenjin hooks enable|disable`\n * are two spellings of this call and never two writers.\n */\nexport async function persistHookArm(dir: string, arm: HookArm, value: boolean): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [arm]: value },\n }));\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Remember, or forget, a project directory this machine wired with\n * `install --project`. `tenjin update` spawns its refresh from the HOME\n * directory, so a project install is unfindable by looking around; this list is\n * how a later refresh reaches it. Absolute paths, de-duplicated, and pruned\n * when a project is uninstalled or its settings file stops carrying our\n * entries.\n */\nexport async function persistRouterProject(\n dir: string,\n projectDir: string,\n present = true,\n): Promise<void> {\n await persist(dir, (existing) => {\n const known = new Set(existing.install?.routerProjects ?? []);\n if (present) known.add(projectDir);\n else known.delete(projectDir);\n return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };\n });\n}\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\nexport interface RouterDefaultsResult {\n /** Keys this run wrote, because the file did not name them. */\n set: string[];\n /** Keys the operator had already written, left exactly as they are. */\n kept: string[];\n removed: string[];\n}\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** Remove/report retired keys in the same locked write. Refresh preserves absent\n * current settings; a fresh install fills only missing automatic limits, with the\n * values the person at the terminal approved or chose. */\nexport async function persistRouterDefaults(\n dir: string,\n refresh = false,\n limits: RouterLimits = ROUTER_DEFAULTS,\n): Promise<RouterDefaultsResult> {\n const result: RouterDefaultsResult = { set: [], kept: [], removed: [] };\n if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;\n await persist(dir, (existing) => {\n const next: PartialConfig = { ...existing };\n result.removed = retiredPaymentKeys(existing);\n for (const key of result.removed) delete next[key];\n if (refresh) return next;\n for (const [key, value] of Object.entries(limits) as [keyof RouterLimits, string][]) {\n if (existing[key] === undefined) {\n next[key] = value;\n result.set.push(key);\n } else result.kept.push(key);\n }\n return next;\n });\n return result;\n}\n\n/**\n * Record the settled harness selection through the same locked merge-write. It\n * replaces the previous record rather than unioning with it: the last operator\n * answer is the current intent. Doctor still re-probes detection independently;\n * the record keeps a deliberately selected but currently undetected harness in play.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly Harness[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\n/**\n * Record the EXACT free-verb rules `install` declined, through the same locked\n * read-modify-write every `config set` uses. Set to whatever was pending at the\n * moment of `--no-grant`; cleared back to `[]` the moment an install\n * actually wires the allowlist, or finds it already fully satisfied. `--refresh` subtracts this list from what it would otherwise\n * report as pending, so a settled no stays settled per rule — without also\n * silencing a genuinely NEW rule a later version adds (tenjin-agent#234).\n */\nexport async function persistGrantDeclined(dir: string, declined: string[]): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, grantDeclined: declined },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if (key === 'bazaarPay' || key === 'confirm') {\n throw new CliError('USAGE', `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });\n }\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n if (key === 'publish.ackServerWarnings') {\n return {\n value: settings.publishAckServerWarnings.value,\n source: settings.publishAckServerWarnings.source,\n };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: the arm's boolean and where it came from. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const { value, source } = settings.hooks[key.slice('hooks.'.length) as HookArm];\n return { value, source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n // REDACTED IN THE MACHINE ENVELOPE TOO, not just in the human line. `config\n // --json` is what an agent reads and what a bug report pastes, and the whole\n // point of a door key is that it opens the door for whoever holds it. What a\n // caller actually needs from this key is whether team mode is on, and\n // set/unset says exactly that. The value is still readable, by the operator,\n // in ~/.tenjin/config.json.\n if (key === 'shelfBypassSecret') {\n return { value: typeof stored === 'string' && stored.length > 0 ? 'set' : 'unset' };\n }\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'sessionBudget' && stored === 'none') return { value: null };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'sessionBudget':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'maxAutoSpend':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'publicShelfUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'shelfBypassSecret':\n // A free string: it is whatever Vercel generated. Empty clears it, which\n // is how team mode is turned back off.\n return value.trim();\n case 'evalCohort':\n return parseBoolean(value);\n case 'bazaarRegistries':\n return parseRegistryList(value);\n }\n}\n\n/** \"\" clears to []; comma-split, each entry an absolute http(s) URL. */\nfunction parseRegistryList(value: string): string[] {\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n .map((entry) => parseHttpUrl(entry));\n}\n\n// Boolean settings accept both on/off and true/false.\nfunction parseBoolean(value: string): boolean {\n if (value === 'true' || value === 'on') return true;\n if (value === 'false' || value === 'off') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\" (or \"true\"/\"false\").',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n // 0600, matching lib/config.ts's `writeConfig`: this file holds\n // `shelfBypassSecret`, and this is the writer `config set` uses to put it\n // there. See that function for why dirMode alone is not enough.\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n // A router key from a project names its file: which of several is in force is the question.\n const where =\n entry.path !== undefined && (entry.source === 'project' || entry.source === 'local')\n ? ` ${entry.path}`\n : '';\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source}${where})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (value === null) return 'none (no daily limit)';\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n return value; // 'always', baseUrl, rpcUrl\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\nexport const RETIRED_SKILL_NAMES = ['tenjin-pay'] as const;\n\n/** Retired names remain known to uninstall, but are never packaged or healed. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n */\nexport const SHIPPED_SKILL_FILES: Record<\n SkillName | (typeof RETIRED_SKILL_NAMES)[number],\n readonly string[]\n> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import type { Harness, HarnessAdapter } from '../adapters/types';\nimport { registeredHooks } from './harness-hooks';\nimport { detectHarnesses, harnessInPlay, harnessTargetDir, onPath } from './skill-wiring';\n\n/**\n * Is one adapter part of this machine's settled installation?\n *\n * An explicit install selection outranks current detection; homes predating\n * that record fall back to the harness directory/PATH probes. Registered hook\n * entries are final evidence, so config and doctor agree even if the binary or\n * home-directory marker later moves.\n */\nexport async function installedHarnessInPlay(\n adapter: HarnessAdapter,\n home: string,\n dataDir: string,\n options: {\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n requested?: readonly Harness[];\n } = {},\n): Promise<boolean> {\n const env = options.env ?? process.env;\n const which = options.which ?? ((bin: string) => onPath(bin, env));\n if (\n harnessInPlay(\n home,\n harnessTargetDir(home, adapter.id),\n detectHarnesses(home, which),\n options.requested ?? [],\n )\n ) {\n return true;\n }\n return (await registeredHooks(adapter, home, dataDir, env)).entries > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,WAAAA,gBAAe;AACxB,SAAS,iBAAiB;;;ACH1B,SAAS,YAAY,gBAAgB;AACrC,SAAS,WAAW,YAAY;AAGhC,SAAS,WAAW,QAAAC,aAAY;;;ACHhC,SAAS,SAAS,YAAY;AASvB,IAAM,cAAc,CAAC,iBAAiB,kBAAkB,QAAQ;AAGhE,IAAM,sBAAsB,CAAC,YAAY;AAGzC,IAAM,uBAAuB,CAAC,GAAG,WAAW;AAe5C,IAAM,sBAGT;AAAA,EACF,iBAAiB,CAAC,YAAY,2BAA2B;AAAA,EACzD,kBAAkB,CAAC,YAAY,wBAAwB;AAAA,EACvD,QAAQ,CAAC,UAAU;AAAA,EACnB,cAAc,CAAC,UAAU;AAC3B;AAIA,IAAM,WAAW,KAAK,UAAU,UAAU;;;AD3BnC,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AACF;AA6BO,SAAS,cAAc,MAAwB;AACpD,SAAO,CAACC,MAAK,MAAM,WAAW,QAAQ,GAAGA,MAAK,MAAM,WAAW,QAAQ,C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C;AAChF,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,UAAU,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AAC5E;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,SAAO;AACT;","names":["dirname","join","join","open","settings","entry","dirname"]}
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-EGELTSPU.js";
28
28
  import {
29
29
  USDC_ADDRESS
30
- } from "./chunk-P22ZWXFX.js";
30
+ } from "./chunk-XICKN3CH.js";
31
31
 
32
32
  // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/contracts.js
33
33
  var contracts = {
@@ -318,4 +318,4 @@ export {
318
318
  prepareUsdcSend,
319
319
  broadcastUsdcSend
320
320
  };
321
- //# sourceMappingURL=chunk-FFL5M5BC.js.map
321
+ //# sourceMappingURL=chunk-YTM7OURD.js.map