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

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 (131) hide show
  1. package/README.md +35 -2
  2. package/dist/{buy-X4VPHFUA.js → buy-2JBYPHAI.js} +16 -14
  3. package/dist/{chunk-6JKD46OJ.js → chunk-3ZW7HPY5.js} +4 -4
  4. package/dist/chunk-4UHNXY6B.js +786 -0
  5. package/dist/chunk-4UHNXY6B.js.map +1 -0
  6. package/dist/{chunk-IFPKA32J.js → chunk-4Y53PDH6.js} +2 -2
  7. package/dist/{chunk-SPUORKD7.js → chunk-54AJIO3E.js} +11 -12
  8. package/dist/chunk-54AJIO3E.js.map +1 -0
  9. package/dist/{chunk-JVBMPU5G.js → chunk-7GJQ5RGA.js} +5 -3
  10. package/dist/{chunk-JVBMPU5G.js.map → chunk-7GJQ5RGA.js.map} +1 -1
  11. package/dist/{chunk-BRAVLUGI.js → chunk-7NADDA2V.js} +9 -6
  12. package/dist/{chunk-BRAVLUGI.js.map → chunk-7NADDA2V.js.map} +1 -1
  13. package/dist/{chunk-T4UWMVKV.js → chunk-ACBEHJAH.js} +4 -4
  14. package/dist/{chunk-XXY77EZJ.js → chunk-DAZAXFSF.js} +7 -7
  15. package/dist/{chunk-OE36HRWG.js → chunk-DTCXO7HS.js} +257 -405
  16. package/dist/chunk-DTCXO7HS.js.map +1 -0
  17. package/dist/{chunk-CA3JV7FX.js → chunk-ETKZWJ4B.js} +2 -2
  18. package/dist/{chunk-CA3JV7FX.js.map → chunk-ETKZWJ4B.js.map} +1 -1
  19. package/dist/{chunk-NKN4YC5C.js → chunk-FDUD3W5V.js} +2 -2
  20. package/dist/{chunk-L4XNT3UW.js → chunk-GEHL43VE.js} +49 -17
  21. package/dist/chunk-GEHL43VE.js.map +1 -0
  22. package/dist/chunk-IU2HVT3Y.js +313 -0
  23. package/dist/chunk-IU2HVT3Y.js.map +1 -0
  24. package/dist/{chunk-OXUJ3FXU.js → chunk-IUQZ4Z7M.js} +36 -8
  25. package/dist/chunk-IUQZ4Z7M.js.map +1 -0
  26. package/dist/{chunk-YMUJZWHB.js → chunk-IXZJ3JOO.js} +5 -5
  27. package/dist/{chunk-47YKYDOF.js → chunk-L6G35FU5.js} +2 -2
  28. package/dist/{chunk-ELVDOTU7.js → chunk-LSWP7MU2.js} +4 -4
  29. package/dist/chunk-LSWP7MU2.js.map +1 -0
  30. package/dist/{chunk-OUJDDY5L.js → chunk-MJSXP4LW.js} +30 -28
  31. package/dist/chunk-MJSXP4LW.js.map +1 -0
  32. package/dist/{chunk-WVHPGQH5.js → chunk-NAAMHWSI.js} +5 -2
  33. package/dist/chunk-NAAMHWSI.js.map +1 -0
  34. package/dist/{chunk-IKAJSA7E.js → chunk-O75FOHXS.js} +29 -11
  35. package/dist/chunk-O75FOHXS.js.map +1 -0
  36. package/dist/{chunk-WMFRCSNC.js → chunk-PCX2JQ2J.js} +3 -3
  37. package/dist/{chunk-IGHSLJUF.js → chunk-PKW3H26Z.js} +5 -5
  38. package/dist/{chunk-3NZCU6SD.js → chunk-PQZVDCCA.js} +4 -4
  39. package/dist/{chunk-OC3EIDCP.js → chunk-QWBUKIP2.js} +7 -1
  40. package/dist/chunk-QWBUKIP2.js.map +1 -0
  41. package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
  42. package/dist/chunk-UO22YNY4.js.map +1 -0
  43. package/dist/chunk-VEAERJVJ.js +43 -0
  44. package/dist/chunk-VEAERJVJ.js.map +1 -0
  45. package/dist/{chunk-GCGMXA2O.js → chunk-VRPLZERE.js} +16 -5
  46. package/dist/chunk-VRPLZERE.js.map +1 -0
  47. package/dist/{chunk-IAR25V2E.js → chunk-W4VW5XYB.js} +4 -4
  48. package/dist/chunk-WYLMJQVH.js +240 -0
  49. package/dist/chunk-WYLMJQVH.js.map +1 -0
  50. package/dist/{chunk-TXVC46SA.js → chunk-XVPQGCH4.js} +11 -10
  51. package/dist/chunk-XVPQGCH4.js.map +1 -0
  52. package/dist/chunk-ZOBNS7CX.js +73 -0
  53. package/dist/chunk-ZOBNS7CX.js.map +1 -0
  54. package/dist/{cli-XK5JZWU6.js → cli-U2BEUA55.js} +34 -36
  55. package/dist/{cli-XK5JZWU6.js.map → cli-U2BEUA55.js.map} +1 -1
  56. package/dist/{config-CNK7MYUR.js → config-CNUIX23Q.js} +12 -6
  57. package/dist/{doctor-R7N7FUX5.js → doctor-QJJXRWTO.js} +11 -7
  58. package/dist/{edit-QSUEG7CL.js → edit-HJ44P44P.js} +13 -11
  59. package/dist/{fund-JF6A76YS.js → fund-Y5IAHZ5D.js} +10 -8
  60. package/dist/index.js +1 -1
  61. package/dist/{inspect-NFNAA4LA.js → inspect-NFQ6SQQQ.js} +14 -12
  62. package/dist/{install-YQVM3SUW.js → install-DXX7PVUP.js} +122 -401
  63. package/dist/install-DXX7PVUP.js.map +1 -0
  64. package/dist/outcome-ANV4QIED.js +24 -0
  65. package/dist/{publish-O2I6IAEL.js → publish-PCBTCXCZ.js} +14 -12
  66. package/dist/{read-UF7QVQOU.js → read-W7QVRBVD.js} +14 -12
  67. package/dist/{read-UF7QVQOU.js.map → read-W7QVRBVD.js.map} +1 -1
  68. package/dist/{run-GDZWHNWZ.js → run-CJWPGMIQ.js} +26 -24
  69. package/dist/{run-GDZWHNWZ.js.map → run-CJWPGMIQ.js.map} +1 -1
  70. package/dist/search-JGAVKTYJ.js +25 -0
  71. package/dist/{send-SI254H3R.js → send-C5EOKXOU.js} +7 -6
  72. package/dist/{send-SI254H3R.js.map → send-C5EOKXOU.js.map} +1 -1
  73. package/dist/{session-GJZJEXLJ.js → session-OBCUUIFX.js} +7 -6
  74. package/dist/{session-GJZJEXLJ.js.map → session-OBCUUIFX.js.map} +1 -1
  75. package/dist/{skill-heal-BPFT22XS.js → skill-heal-D6EPLPS6.js} +3 -3
  76. package/dist/skill-heal-D6EPLPS6.js.map +1 -0
  77. package/dist/{uninstall-7ZZG6WQ5.js → uninstall-OWJNJ5LI.js} +11 -5
  78. package/dist/uninstall-OWJNJ5LI.js.map +1 -0
  79. package/dist/{update-FPSBITLB.js → update-24Y2CQTT.js} +16 -13
  80. package/dist/update-24Y2CQTT.js.map +1 -0
  81. package/dist/{wallet-TZVD2M4I.js → wallet-OFXDIIGP.js} +7 -6
  82. package/dist/{wallet-NS7TYWNN.js → wallet-SLRIYJ2U.js} +4 -3
  83. package/docs/agent-permissions.md +100 -16
  84. package/docs/command-reference.md +21 -11
  85. package/package.json +1 -1
  86. package/skills/tenjin-publish/SKILL.md +181 -205
  87. package/skills/tenjin-publish/references/maintain.md +39 -0
  88. package/skills/tenjin-search/SKILL.md +86 -279
  89. package/skills/tenjin-search/references/permissions.md +106 -0
  90. package/dist/chunk-ELVDOTU7.js.map +0 -1
  91. package/dist/chunk-FKSAUOJU.js.map +0 -1
  92. package/dist/chunk-GCGMXA2O.js.map +0 -1
  93. package/dist/chunk-IKAJSA7E.js.map +0 -1
  94. package/dist/chunk-L4XNT3UW.js.map +0 -1
  95. package/dist/chunk-OC3EIDCP.js.map +0 -1
  96. package/dist/chunk-OE36HRWG.js.map +0 -1
  97. package/dist/chunk-OUJDDY5L.js.map +0 -1
  98. package/dist/chunk-OXUJ3FXU.js.map +0 -1
  99. package/dist/chunk-SPUORKD7.js.map +0 -1
  100. package/dist/chunk-TXVC46SA.js.map +0 -1
  101. package/dist/chunk-UUARTUY2.js +0 -349
  102. package/dist/chunk-UUARTUY2.js.map +0 -1
  103. package/dist/chunk-WVHPGQH5.js.map +0 -1
  104. package/dist/install-YQVM3SUW.js.map +0 -1
  105. package/dist/outcome-IUSYFJTN.js +0 -22
  106. package/dist/search-JVOHEF3E.js +0 -23
  107. package/dist/skill-heal-BPFT22XS.js.map +0 -1
  108. package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
  109. package/dist/update-FPSBITLB.js.map +0 -1
  110. /package/dist/{buy-X4VPHFUA.js.map → buy-2JBYPHAI.js.map} +0 -0
  111. /package/dist/{chunk-6JKD46OJ.js.map → chunk-3ZW7HPY5.js.map} +0 -0
  112. /package/dist/{chunk-IFPKA32J.js.map → chunk-4Y53PDH6.js.map} +0 -0
  113. /package/dist/{chunk-T4UWMVKV.js.map → chunk-ACBEHJAH.js.map} +0 -0
  114. /package/dist/{chunk-XXY77EZJ.js.map → chunk-DAZAXFSF.js.map} +0 -0
  115. /package/dist/{chunk-NKN4YC5C.js.map → chunk-FDUD3W5V.js.map} +0 -0
  116. /package/dist/{chunk-YMUJZWHB.js.map → chunk-IXZJ3JOO.js.map} +0 -0
  117. /package/dist/{chunk-47YKYDOF.js.map → chunk-L6G35FU5.js.map} +0 -0
  118. /package/dist/{chunk-WMFRCSNC.js.map → chunk-PCX2JQ2J.js.map} +0 -0
  119. /package/dist/{chunk-IGHSLJUF.js.map → chunk-PKW3H26Z.js.map} +0 -0
  120. /package/dist/{chunk-3NZCU6SD.js.map → chunk-PQZVDCCA.js.map} +0 -0
  121. /package/dist/{chunk-IAR25V2E.js.map → chunk-W4VW5XYB.js.map} +0 -0
  122. /package/dist/{config-CNK7MYUR.js.map → config-CNUIX23Q.js.map} +0 -0
  123. /package/dist/{doctor-R7N7FUX5.js.map → doctor-QJJXRWTO.js.map} +0 -0
  124. /package/dist/{edit-QSUEG7CL.js.map → edit-HJ44P44P.js.map} +0 -0
  125. /package/dist/{fund-JF6A76YS.js.map → fund-Y5IAHZ5D.js.map} +0 -0
  126. /package/dist/{inspect-NFNAA4LA.js.map → inspect-NFQ6SQQQ.js.map} +0 -0
  127. /package/dist/{outcome-IUSYFJTN.js.map → outcome-ANV4QIED.js.map} +0 -0
  128. /package/dist/{publish-O2I6IAEL.js.map → publish-PCBTCXCZ.js.map} +0 -0
  129. /package/dist/{search-JVOHEF3E.js.map → search-JGAVKTYJ.js.map} +0 -0
  130. /package/dist/{wallet-NS7TYWNN.js.map → wallet-OFXDIIGP.js.map} +0 -0
  131. /package/dist/{wallet-TZVD2M4I.js.map → wallet-SLRIYJ2U.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/install.ts","../src/lib/harness-hooks.ts","../src/lib/clack.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from '../lib/errors';\nimport { hasCode } from '../lib/errno';\nimport { ownsAnyLock, releaseOwnedLocks } from '../lib/lock';\nimport { installSkill } from '../lib/skill-writer';\nimport type { SkillInstallStatus } from '../lib/skill-writer';\nimport { resolveSkillsSource, SKILL_NAMES } from '../lib/skills-source';\nimport {\n CLI_SKILL_NAMES,\n HARNESS_TARGETS,\n HOSTED_SKILL_NAME,\n harnessDetectedBy,\n harnessTargetDir,\n isModelInvocationDisabled,\n onPath,\n readSkillFile,\n} from '../lib/skill-wiring';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n PublishModeSchema,\n SearchHookModeSchema,\n parsePublishModeFlag,\n parseSearchHookModeFlag,\n} from '../lib/config';\nimport type { PublishMode, SearchHookMode } from '../lib/config';\nimport { persistInstallHarness, persistPublishMode, persistSearchHookMode } from './config';\nimport { runWalletCreate } from './wallet';\nimport { collectDoctorChecks, isNoWalletCheck } from './doctor';\nimport type { DoctorDeps, DoctorChecks } from './doctor';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { walletPath } from '../lib/paths';\nimport { PERMISSIONS_DOC_URL, recommendedPermissions } from '../lib/permissions';\nimport {\n FREE_VERB_RULES,\n inspectFreeVerbRules,\n permissionsSkipped,\n wireFreeVerbAllowlist,\n} from '../lib/harness-permissions';\nimport type { PermissionsResult } from '../lib/harness-permissions';\nimport { hooksSkipped, hooksUndo, wireSearchHooks } from '../lib/harness-hooks';\nimport { removeMarkerLines } from '../lib/uninstall';\nimport type { HooksResult } from '../lib/harness-hooks';\nimport { confirmChoice, intro as clackIntro, outro as clackOutro, selectOne } from '../lib/clack';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { Io } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n// The `--harness` vocabulary and its directory mapping are single-sourced in\n// skill-wiring beside the detection probes, because `doctor` maps a persisted choice\n// back to a directory with the same rules.\nconst HARNESSES = HARNESS_TARGETS;\ntype Harness = HarnessTarget;\n\nconst InstallInputSchema = z.object({\n harness: z.array(z.string()).optional(),\n dryRun: z.boolean().optional(),\n publishMode: z.string().optional(),\n noWallet: z.boolean().optional(),\n /**\n * ACCEPTED AND IGNORED. `install` writes no CLAUDE.md/AGENTS.md line any more —\n * a skill's own frontmatter description is the trigger surface the harness reads\n * at session start, so the line only duplicated it. Both spellings still parse so\n * a script or a released doc that passes one does not fail; neither does anything.\n */\n claudeMd: z.boolean().optional(),\n /**\n * Tri-state. `true` (`--allow-free-verbs`) wires the free-verb\n * allowlist without asking, which is now also what an unanswered non-interactive\n * run does, so the flag is kept for compatibility and as an explicit statement of\n * intent. `false` (`--no-allow-free-verbs`) is the opt-out and is the only way to\n * get a run that writes no permission rule. `undefined` asks when it can, and\n * writes when it cannot ask.\n */\n allowFreeVerbs: z.boolean().optional(),\n /** The harness search-hook behavior to install (`--search-hooks auto|remind|off`). */\n searchHooks: z.string().optional(),\n /**\n * `--no-hooks`: register no hooks THIS RUN, changing nothing persistent. It is\n * deliberately not the same as `--search-hooks off`, which is a durable\n * statement about behavior and writes `hooks.searchMode: off` to config.\n */\n noHooks: z.boolean().optional(),\n});\nexport type InstallInput = z.infer<typeof InstallInputSchema>;\n\n/**\n * The publish-mode question's seam: returns the chosen mode, or `null` when the\n * operator cancelled (which changes nothing and writes nothing). The choices\n * themselves are {@link PUBLISH_MODE_CHOICES}; the seam exists so tests answer\n * in-process and never render a prompt.\n */\nexport type PromptPublishModeFn = () => Promise<PublishMode | null>;\n\n/** A yes/no seam, same shape as buy's `confirm`. */\nexport type ConfirmFn = (label: string) => Promise<boolean>;\n\ntype PublishModeSource = 'flag' | 'existing' | 'prompt' | 'headless-default' | 'default-skipped';\ninterface PublishModeSelection {\n value: PublishMode;\n source: PublishModeSource;\n}\n\n/**\n * Why no wallet was created, when none was.\n *\n * `no-passphrase-store` is the one that matters: this machine has no OS\n * credential store that would hold a generated passphrase, and no\n * `TENJIN_WALLET_PASSPHRASE`. There is no fallback here BY DESIGN. A passphrase\n * written to a plain file beside the keystore it unlocks is not a passphrase, so\n * the run creates nothing and says so loudly with both remedies.\n */\ntype WalletSkipReason = 'no-passphrase-store' | 'create-failed' | 'dry-run' | 'flag';\n\n/**\n * How the wallet step resolved, so rendering stays separate from prompting.\n *\n * `declined` (an answer) and `skipped` (no answer, with a reason) are kept apart\n * deliberately: an install that could not create a key is a different state from\n * one the operator told not to, and only the first needs a remedy.\n */\ninterface WalletOutcome {\n status: 'existing' | 'created' | 'declined' | 'skipped';\n address?: string;\n /** Only ever set on `skipped`. */\n reason?: WalletSkipReason;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n /** The underlying failure, for a `create-failed` skip. */\n warning?: string;\n}\n\n/** The remedy for each skip, so no skipped state is ever a dead end. */\nfunction walletFix(reason: WalletSkipReason): string {\n switch (reason) {\n case 'no-passphrase-store':\n return 'No OS credential store is available to hold the wallet passphrase. Set TENJIN_WALLET_PASSPHRASE and re-run `tenjin install`, or run `tenjin wallet create` in a terminal to enter one.';\n case 'create-failed':\n return 'Fix the reported problem, then run `tenjin wallet create`.';\n case 'dry-run':\n case 'flag':\n return 'Create one with `tenjin wallet create`.';\n }\n}\n\n/**\n * The Codex config.toml rule the user must add by hand. We PRINT it, never edit\n * config.toml: Codex's default workspace-write sandbox blocks network, which would\n * make every paid x402 call fail (or prompt) until this is set.\n */\nconst CODEX_NETWORK_RULE = '[sandbox_workspace_write]\\nnetwork_access = true';\n\n/** Per-skill install outcome for one harness target. */\ninterface SkillResult {\n name: string;\n status: SkillInstallStatus;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n /** Is this one of the two CLI adapter skills (as opposed to the hosted mirror)? */\n cli: boolean;\n /** Will a harness surface it to the model after this run? On a --dry-run nothing is\n * written, so it answers for the packaged copy that would land. */\n modelInvocable: boolean;\n}\n\ninterface HarnessResult {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n skills: SkillResult[];\n /**\n * Was the hosted zero-install `tenjin` skill already in this target before the\n * run? Reported so an upgrade over a hosted-skill machine is visible in `--json`,\n * which is exactly the state #35 was invisible in.\n */\n hostedPreexisting: boolean;\n /**\n * Narrower than {@link HarnessResult.hostedPreexisting}: the hosted skill was here\n * AND the CLI adapters were not, which is the hosted-zero-install-first funnel\n * rather than a second run finding our own mirror. This is what gates the notice.\n */\n hostedArrivedFirst: boolean;\n codexNetworkRule?: string;\n notes: string[];\n warnings: string[];\n}\n\nexport interface InstallDeps {\n /** Home directory root for harness detection + skill destinations. Tests inject a temp dir. */\n homeDir?: string;\n /** The packaged skills source directory. Defaults to resolving it from this module's location. */\n skillsSourceDir?: string;\n /** PATH probe for `claude`/`codex` binaries. Injectable so tests never depend on the real PATH. */\n which?: (bin: string) => boolean;\n /** Environment (PATH for the default `which`). Defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Doctor check collector; defaults to the real one. Injected in tests to avoid the network. */\n collectChecks?: (ctx: CommandContext) => Promise<DoctorChecks>;\n /** Deps forwarded to the default doctor collector (e.g. a canned fetch). */\n doctorDeps?: DoctorDeps;\n /** Decision 1: the publish-mode select; defaults to the clack list. */\n promptPublishMode?: PromptPublishModeFn;\n /** Decision 2: the permissions confirm (default yes); defaults to the clack confirm. */\n confirmPermissions?: ConfirmFn;\n /** Whether decision 2 has anything left to grant; defaults to reading settings.json. */\n inspectPermissions?: (\n home: string,\n ) => Promise<{ pending: string[] | null; satisfied?: PermissionsResult }>;\n /** Decision 3: the search-hook mode select; defaults to the clack list. */\n promptSearchHooks?: () => Promise<SearchHookMode | null>;\n /** Decision 4: \"Create a wallet now?\"; defaults to the clack confirm (default yes). */\n confirmWallet?: ConfirmFn;\n /** Prompt-sequence chrome. Seams so tests never load the renderer. */\n intro?: (message: string) => Promise<void>;\n outro?: (message: string) => Promise<void>;\n /** Whether the human walkthrough runs (TTY, no --json, stdin is a TTY). Injected in tests. */\n isInteractive?: boolean;\n /** Does a wallet already exist? Defaults to walletFileExists(dataDir). */\n walletExists?: (dataDir: string) => Promise<boolean>;\n /** An existing wallet's address, for the \"(existing)\" line. Defaults to the local provider. */\n walletAddress?: (ctx: CommandContext) => Promise<string>;\n /** Create a wallet and return its address. Defaults to runWalletCreate. */\n createWallet?: (ctx: CommandContext) => Promise<string>;\n /**\n * Passphrase-resolution seam forwarded to `wallet create` (OS-store exec, TTY\n * prompt, platform). Tests MUST set it: without it a headless install now\n * creates a real wallet, and on macOS that writes to the developer's own login\n * keychain under the `tenjin-cli` service.\n */\n walletPassphrase?: PassphraseOverrides;\n}\n\n/**\n * `tenjin install`: detect the installed harness(es), copy the packaged skills\n * into each one's skills directory, wire the AGENTS.md pointer, ask AT MOST FOUR\n * questions (publishing, harness permissions, search hooks, wallet), then run the\n * doctor checks over the machine those answers just produced and print a short\n * summary. Everything that is not one of those four decisions is display: the\n * security reference material lives in docs/agent-permissions.md, not in the\n * middle of a setup flow.\n *\n * A NON-INTERACTIVE RUN IS A USABLE INSTALL, not a stripped one. The permission\n * allowlist, the search hooks, the CLAUDE.md nudge and the wallet are all settled\n * by default when there is no one to ask, because the machine that most needs\n * them is exactly the one running headless. Each is disclosed in the output with\n * its undo and each has an opt-out flag.\n *\n * Like every command it is human-first (the global output contract): at a TTY\n * without `--json` it prompts and returns the walkthrough as humanLines, which\n * the dispatcher prints to stdout with no envelope. With `--json` or piped\n * stdout it returns the envelope and asks nothing. Idempotent: a re-run reports\n * up-to-date, never duplicates the AGENTS.md line, adds no permission rule twice,\n * and registers no hook twice. `--dry-run` writes nothing.\n */\nexport async function runInstall(\n input: InstallInput,\n ctx: CommandContext,\n deps: InstallDeps = {},\n): Promise<CommandResult> {\n return withInterruptGuard((markPhase) => installBody(input, ctx, deps, markPhase));\n}\n\n/** How far the command got, for the interrupt diagnostic. */\ntype InstallPhase = 'writing-skills' | 'wired';\n\n/**\n * Run `fn` with SIGINT/SIGTERM answered for the WHOLE command, not just the\n * blocks that hold a lock. The default signal action terminates without running\n * `finally`, stranding whichever lock the command holds so every later run times\n * out on it; install takes two (the config lock behind decision 1, and the\n * wallet-create lock behind decision 3, whose scrypt work is the longest\n * interruptible window this command has). Ownership is tracked by the lock\n * itself, so the handler releases exactly what this process holds and a run still\n * QUEUED behind another cannot touch that other run's lock.\n *\n * `markPhase` carries the diagnostic past the states no lock covers: the skills\n * write holds nothing (each file lands by its own atomic rename), so without it an\n * interrupt mid-copy would report that nothing changed.\n */\nasync function withInterruptGuard(\n fn: (markPhase: (phase: InstallPhase) => void) => Promise<CommandResult>,\n): Promise<CommandResult> {\n let phase: InstallPhase | undefined;\n const onSignal = (signal: NodeJS.Signals): void => {\n const wasWriting = ownsAnyLock() || phase === 'writing-skills';\n releaseOwnedLocks();\n // An external SIGINT/SIGTERM can land while a clack prompt has the terminal\n // in raw mode with the cursor hidden; process.exit skips clack's teardown.\n // (Ctrl-C at a prompt is unaffected: raw mode delivers it as a keypress.)\n if (process.stdin.isTTY) process.stdin.setRawMode?.(false);\n if (process.stdout.isTTY) process.stdout.write('\\x1b[?25h');\n process.stderr.write(\n wasWriting\n ? `\\nInterrupted mid-write. Some files may be half-written; re-run \\`tenjin install\\` to finish.\\n`\n : phase === 'wired'\n ? `\\nInterrupted after the skills were written; later setup steps may not have finished. Re-run \\`tenjin install\\` to finish.\\n`\n : '\\nInterrupted before anything was written; nothing changed.\\n',\n );\n process.exit(signal === 'SIGINT' ? 130 : 143);\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n try {\n return await fn((p) => {\n phase = p;\n });\n } finally {\n process.off('SIGINT', onSignal);\n process.off('SIGTERM', onSignal);\n }\n}\n\nasync function installBody(\n input: InstallInput,\n ctx: CommandContext,\n deps: InstallDeps,\n markPhase: (phase: InstallPhase) => void,\n): Promise<CommandResult> {\n const parsed = InstallInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new CliError('USAGE', 'Invalid install options', {\n fix: 'Run `tenjin install --help`.',\n details: parsed.error.issues,\n });\n }\n const dryRun = parsed.data.dryRun === true;\n const noWallet = parsed.data.noWallet === true;\n const noHooks = parsed.data.noHooks === true;\n const allowFreeVerbs = parsed.data.allowFreeVerbs;\n // Validate the enum flags UP FRONT so a bad value fails before any wiring.\n const publishModeFlag =\n parsed.data.publishMode !== undefined ? parseModeFlag(parsed.data.publishMode) : undefined;\n const searchHooksFlag =\n parsed.data.searchHooks !== undefined\n ? parseSearchHookModeFlag(parsed.data.searchHooks, '--search-hooks')\n : undefined;\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n // An empty or relative HOME (sudo/docker env_reset, systemd units) would make\n // every target below relative, silently installing into the current working\n // directory and reporting success while no harness reads a thing.\n if (!isAbsolute(home)) {\n throw new CliError(\n 'INTERNAL',\n 'The home directory did not resolve to an absolute path, so nothing was installed.',\n {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n },\n );\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n\n // Human-first is the global output rule (emitSuccess renders humanLines at a TTY\n // without --json and no envelope). `humanOutput` matches that gate so install\n // returns its walkthrough as humanLines; `canPrompt` additionally needs stdin, so\n // a piped-stdin run still renders a walkthrough (with defaults, no wallet prompt).\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n\n const skillsSource =\n deps.skillsSourceDir ?? resolveSkillsSource(fileURLToPath(new URL('.', import.meta.url)));\n await assertSkillsSource(skillsSource);\n\n const plans = resolvePlans(parsed.data.harness, home, which);\n // Same condition resolvePlans treats as an override, so what gets recorded below is\n // exactly what overrode detection.\n const explicitHarness = parsed.data.harness !== undefined && parsed.data.harness.length > 0;\n // The CLAUDE.md nudge is written BY DEFAULT, on both paths, only\n // `--no-claude-md` suppresses it. Codex already got the same line in its\n const harnesses: HarnessResult[] = [];\n // Unlocked. What makes concurrent writers safe here is the per-file atomic\n // rename, not serialization: the rm-then-write this used to be had two runs\n // reading each other's half-built trees (7 of 15 concurrent runs failed on raw\n // ENOENT/ENOTEMPTY renames), and 24 concurrent runs pass without a lock. The\n // self-heal is the other writer, and it writes these same bytes to these same\n // paths through the same writer.\n if (!dryRun) markPhase('writing-skills');\n for (const plan of plans) {\n harnesses.push(await applyPlan(plan, skillsSource, dryRun));\n }\n await assertSkillsLanded(plans, dryRun);\n if (!dryRun) markPhase('wired');\n // An explicit --harness is REMEMBERED, before the embedded doctor run so this run's\n // own check already honours it. Detection cannot see a harness we do not probe for,\n // so without the record a directory the user named by hand is a target for one run\n // and then invisible to every later doctor — including for the #35 shadowing defect\n // it was chosen to hold. `--dry-run` records nothing, like the publish-mode write.\n if (explicitHarness && !dryRun) {\n await underDataDir(ctx.dataDir, () =>\n persistInstallHarness(\n ctx.dataDir,\n plans.map((p) => p.harness),\n ),\n );\n }\n // One-time cleanup of the pointer line older versions wrote into the operator's\n // CLAUDE.md / AGENTS.md. `install` writes no such line now: a skill's own\n // frontmatter description is the trigger surface the harness loads at session\n // start, so the line only duplicated it. Removing it here is what gets the\n // footprint off machines that already have one, since most people re-run\n // `install` far more often than they would run a cleanup command.\n const pointerCleanup = dryRun ? [] : await removeMarkerLines(home);\n\n // The four decisions, in order. Each one is skipped (with its own recorded\n // reason) when a flag already settled it or when there is no one to ask.\n if (canPrompt) await (deps.intro ?? clackIntro)('tenjin install');\n const publishMode = await underDataDir(ctx.dataDir, () =>\n resolvePublishMode(publishModeFlag, ctx, deps, dryRun, canPrompt),\n );\n const permissions = await resolvePermissions({\n plans,\n home,\n deps,\n flag: allowFreeVerbs,\n dryRun,\n canPrompt,\n });\n const hooks = await underDataDir(ctx.dataDir, () =>\n resolveHooks({ plans, home, ctx, deps, flag: searchHooksFlag, noHooks, dryRun, canPrompt }),\n );\n // On BOTH paths now: the loop this command sets up needs a key, so a headless\n // run creates one rather than leaving the operator a setup that stops at the\n // first buy or publish.\n const wallet = await underDataDir(ctx.dataDir, () =>\n resolveWallet(ctx, deps, walletSkip(dryRun, noWallet), canPrompt),\n );\n\n // AFTER all four decisions, never before (#101). The snapshot used to be taken\n // straight after the skills were written, so a run that created a wallet\n // reported \"No wallet\" in both the walkthrough and `data.doctor` — the checks\n // described a machine that had stopped existing three steps earlier. Collecting\n // here costs nothing extra (it is still one run) and is what makes the embedded\n // report describe the install it is reporting on: the wallet just created, and\n // the config `publish.mode` just written.\n //\n // It still inspects the same `home` install wrote into, so its skill-wiring\n // check reports THIS run's result rather than os.homedir()'s. `which` goes with\n // it: the check gates its verdicts on harness detection, and a different probe\n // there would judge directories this run never targeted.\n const doctorDeps: DoctorDeps = { ...(deps.doctorDeps ?? {}) };\n doctorDeps.homeDir ??= home;\n doctorDeps.which ??= which;\n const collect = deps.collectChecks ?? ((c) => collectDoctorChecks(c, doctorDeps));\n const doctor = await collect(ctx);\n\n if (canPrompt) await (deps.outro ?? clackOutro)('Setup complete.');\n\n const data = {\n dryRun,\n skillsSource,\n harnesses,\n // One-time cleanup, reported because it edits a file the operator owns. Older\n // versions wrote a pointer line into CLAUDE.md/AGENTS.md; nothing writes one\n // now, so an install that finds one removes it and says which file it touched.\n pointerCleanup,\n doctor: { status: doctor.failure !== undefined ? 'fail' : 'pass', checks: doctor.checks },\n publishMode,\n // Shipped with the install rather than left for the operator to discover after\n // their first auto-mode denial (#33). Static constants, no config key: see\n // lib/permissions.ts for why this is deliberately not operator-editable state.\n // `wired` is the outcome of THIS run's settings.json write; the three\n // recommendation tiers beside it are unchanged, so a machine consumer that\n // read `alwaysSafe` / `optIn` / `neverAllowlisted` before still does.\n permissions: { ...recommendedPermissions(), wired: permissions },\n hooks,\n wallet,\n };\n\n // Machine path (--json or piped stdout): the envelope, no prompts.\n if (!humanOutput) return { data };\n\n // Human path: the walkthrough as humanLines (the global emitSuccess prints them\n // to stdout at a TTY and never an envelope).\n const humanLines = buildWalkthrough(ctx.io, {\n pointerCleanup,\n dryRun,\n dataDir: ctx.dataDir,\n harnesses,\n publishMode,\n permissions,\n hooks,\n wallet,\n doctor,\n });\n return { data, humanLines };\n}\n\n/**\n * Why no wallet is being created at all, or undefined when one is. Being unable\n * to prompt is NOT on this list any more: a headless run creates by default.\n */\nfunction walletSkip(dryRun: boolean, noWallet: boolean): 'dry-run' | 'flag' | undefined {\n if (dryRun) return 'dry-run';\n if (noWallet) return 'flag';\n return undefined;\n}\n\n/**\n * The two steps that write to the Tenjin data dir, with a denial there reported as\n * the directory it is rather than as a raw errno under INTERNAL. The skills are\n * already on disk by now, so the message says what failed, not that nothing\n * happened.\n */\nasync function underDataDir<T>(dataDir: string, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (!hasCode(err, 'EACCES') && !hasCode(err, 'EPERM')) throw err;\n throw new CliError('INTERNAL', `Could not use the Tenjin data directory ${dataDir}.`, {\n fix: `Permission denied. Check that you can write to it (\\`ls -ld ${dataDir}\\`), then re-run \\`tenjin install\\`.`,\n cause: err,\n });\n }\n}\n\nconst EXAMPLE_QUESTION = \"what actually changed in <library> v3's public API\";\n\ninterface WalkthroughState {\n dryRun: boolean;\n /** Legacy pointer files this run cleaned; disclosed because they are the\n * operator's own notes and we edited them. */\n pointerCleanup: string[];\n /** Where the wallet keystore lives, for the create disclosure. */\n dataDir: string;\n harnesses: HarnessResult[];\n publishMode: PublishModeSelection;\n permissions: PermissionsResult;\n hooks: HooksResult;\n wallet: WalletOutcome;\n doctor: DoctorChecks;\n}\n\n/**\n * The human surface: what happened, then what still needs you (#80). The summary\n * of at most five lines comes FIRST — it used to sit under the warnings, so a\n * first-time reader met \"Some checks need attention\" before learning anything had\n * succeeded and the whole run read as failure-then-success. On a clean install\n * the summary IS the output.\n *\n * The dry-run banner stays on top: it qualifies every line below it, so it is not\n * an attention item but a statement about what the rest of the output means.\n */\nfunction buildWalkthrough(io: Io, s: WalkthroughState): string[] {\n const lines: string[] = [];\n if (s.dryRun) {\n lines.push(paint(io, 'yellow', 'Dry run: nothing was written.'));\n lines.push('');\n }\n lines.push(...summaryLines(io, s));\n const notices = noticeLines(io, s);\n if (notices.length > 0) lines.push('', ...notices);\n return lines;\n}\n\n/**\n * Everything below the summary: per-harness warnings, the Codex network rule,\n * the nudge disclosure and its undo, and any doctor check that is not ok. A\n * green doctor says nothing at all, so a clean run stays five lines.\n */\nfunction noticeLines(io: Io, s: WalkthroughState): string[] {\n const lines: string[] = [];\n for (const h of s.harnesses) {\n if (h.hostedArrivedFirst) {\n // Named by DIRECTORY: one line per harness, and the funnel puts the mirror\n // in both, so an unqualified line appears twice and reads as a stutter.\n lines.push(\n paint(\n io,\n 'dim',\n `The hosted ${HOSTED_SKILL_NAME} skill was already in ${h.skillsDir}: kept as the zero-install fallback, and the CLI skills now take precedence.`,\n ),\n );\n }\n if (h.codexNetworkRule !== undefined) {\n lines.push(paint(io, 'dim', 'Codex blocks network by default; add to ~/.codex/config.toml:'));\n for (const rl of h.codexNetworkRule.split('\\n')) lines.push(paint(io, 'dim', ` ${rl}`));\n }\n for (const w of h.warnings) lines.push(paint(io, 'yellow', `! ${w}`));\n }\n // Not dim: we edited a file the operator writes their own notes in, and a line\n // saying so is the only way they learn it happened.\n if (s.pointerCleanup.length > 0) {\n lines.push(\n `Removed the old Tenjin pointer line from ${s.pointerCleanup.join(' and ')}; the skills carry their own triggers now.`,\n );\n }\n // Same reason as the pointer line above: we edited the operator's settings.json\n // to REMOVE something, and the only way they learn it happened is a line here.\n if (s.permissions.removed.length > 0) {\n lines.push(\n `Removed ${s.permissions.removed.length} permission rule(s) an older tenjin left in ${s.permissions.path ?? 'your settings'} for commands that no longer exist.`,\n );\n }\n // A run that wired permissions without being asked has to say so, and say how to\n // take it back. This is the disclosure that makes the non-interactive default\n // defensible: nothing lands silently, whether it was answered or defaulted.\n if (s.permissions.added.length > 0) {\n // What landed and how to take it back. NOT the rules themselves: `doctor`\n // prints those in full with their caveats, and reciting nine lines in the\n // middle of a setup flow is what the walkthrough was trimmed of. The machine\n // envelope carries the exact rules in `permissions.wired.added`.\n lines.push(\n paint(\n io,\n 'dim',\n `${s.permissions.added.length} free tenjin commands were allowed in ${s.permissions.path}. None can spend USDC or open your wallet keystore; see them with \\`tenjin doctor\\`.`,\n ),\n );\n lines.push(paint(io, 'dim', `Undo anytime: remove those lines from ${s.permissions.path}.`));\n }\n if (s.hooks.added.length > 0 || s.hooks.updated.length > 0) {\n lines.push(paint(io, 'dim', hooksDisclosure(s.hooks)));\n lines.push(\n paint(io, 'dim', hooksUndo(s.hooks.path ?? '~/.claude/settings.json', s.hooks.scriptsDir)),\n );\n // NOT dim, unlike the disclosure above it: settings.json hooks are read once\n // at session start, so an operator who does not restart gets no hook activity\n // at all and nothing telling them why. That silence is the whole reason this\n // line exists, so it must not read as fine print.\n lines.push(\n `${paint(io, 'bold', 'Restart Claude Code')} to load them; hooks are read once at session start.`,\n );\n }\n if (s.hooks.warning !== undefined) {\n lines.push(paint(io, 'yellow', `! ${sanitizeForTerminal(s.hooks.warning)}`));\n }\n for (const line of walletDisclosure(s.wallet, s.dataDir)) lines.push(paint(io, 'dim', line));\n if (s.wallet.warning !== undefined) {\n lines.push(paint(io, 'yellow', `! ${sanitizeForTerminal(s.wallet.warning)}`));\n }\n if (s.permissions.warning !== undefined) {\n // Sanitized for the same reason doctorNotices sanitizes `detail`/`fix`: this\n // string embeds a V8 JSON parse error, and V8 quotes the offending input, so\n // ~20 bytes of whatever is in settings.json (escapes included) reach the\n // terminal at the moment we tell the operator we left their file alone.\n lines.push(paint(io, 'yellow', `! ${sanitizeForTerminal(s.permissions.warning)}`));\n }\n lines.push(...doctorNotices(io, s.doctor, s.wallet));\n return lines;\n}\n\n/**\n * The closing summary, capped at one line per subject: skills, publishing,\n * permissions, wallet, and the command to run next.\n */\nfunction summaryLines(io: Io, s: WalkthroughState): string[] {\n return [\n ...s.harnesses.map((h) => skillsLine(io, h, s.dryRun)),\n publishingLine(io, s.publishMode.value),\n permissionsLine(io, s.permissions),\n hooksLine(io, s.hooks),\n walletLine(io, s.wallet),\n `${paint(io, 'bold', 'Next:')} tenjin search \"${EXAMPLE_QUESTION}\"`,\n ];\n}\n\n/** What the hooks do, in one line, at the moment they are written. */\nfunction hooksDisclosure(h: HooksResult): string {\n const shared =\n 'A Stop hook reminds you locally when a MISS you searched for is still unpublished; it makes no network call.';\n if (h.mode === 'remind') {\n return `The WebSearch hook prints a one-line reminder that Tenjin may have an answer; it sends nothing off-machine. ${shared}`;\n }\n return `Before a web search, the WebSearch hook asks tenjin.blog the same question (free and anonymous, ~2s budget, 5s harness kill) and mentions a tested answer if one exists; the query text leaves the machine. It can never block or change the search. ${shared}`;\n}\n\n/**\n * One line for the harness hooks. A skip is never silent, for the same reason the\n * permissions line is never silent: the operator would otherwise find out by\n * noticing that nothing ever happens.\n */\nfunction hooksLine(io: Io, h: HooksResult): string {\n const label = paint(io, 'bold', 'Search hooks:');\n const wrote = h.added.length + h.updated.length;\n if (wrote > 0) {\n return `${paint(io, 'green', '✓')} ${label} ${h.mode} mode, ${wrote} hook(s) registered in ${h.path}. Change: tenjin config set hooks.searchMode <auto|remind|off>`;\n }\n if (h.skipped === undefined) {\n return `${paint(io, 'green', '✓')} ${label} ${h.mode} mode, already registered in ${h.path}`;\n }\n if (h.skipped === 'harness-not-claude') {\n return `${paint(io, 'dim', '-')} ${label} not wired (Claude Code only).`;\n }\n if (h.skipped === 'dry-run') {\n return `${paint(io, 'dim', '-')} ${label} unchanged (dry run).`;\n }\n if (h.skipped === 'mode-off') {\n return `${paint(io, 'dim', '-')} ${label} off (hooks.searchMode). Turn them on: tenjin config set hooks.searchMode auto, then tenjin install`;\n }\n if (h.skipped === 'declined') {\n return `${paint(io, 'dim', '-')} ${label} not registered this run; nothing was configured. Register them: tenjin install`;\n }\n if (h.skipped === 'changed-since-read') {\n return `${paint(io, 'yellow', '!')} ${label} ${h.path} changed while it was being updated, so nothing was written. Re-run: tenjin install`;\n }\n return `${paint(io, 'yellow', '!')} ${label} ${h.path} was left untouched. Fix it, then: tenjin install`;\n}\n\nfunction harnessLabel(h: Harness): string {\n return h === 'claude' ? 'Claude Code' : h === 'codex' ? 'Codex' : 'Agent Skills';\n}\n\n/**\n * One line per harness. It names the skills rather than counting them: #35\n * shipped as \"search worked, publish was simply absent\" on a machine that\n * already had the hosted skill, and a bare \"3 skills installed\" cannot tell you\n * publish is wired.\n */\nfunction skillsLine(io: Io, h: HarnessResult, dryRun: boolean): string {\n const changed = h.skills.some((s) => s.status !== 'up-to-date');\n const verb = dryRun ? 'would install' : changed ? 'installed' : 'up to date';\n const head = `${harnessLabel(h.harness)}: ${h.skills.length} skills ${verb}`;\n return `${paint(io, 'green', '✓')} ${paint(io, 'bold', head)} in ${h.skillsDir}. ${skillRoster(h)}.`;\n}\n\n/** One line for the settled consent mode, with the same consequence the question showed. */\nfunction publishingLine(io: Io, mode: PublishMode): string {\n return `${paint(io, 'green', '✓')} ${paint(io, 'bold', `Publishing: ${mode}`)}. ${modeBlurb(mode)}`;\n}\n\n/**\n * One line for the harness allowlist: what landed, or what to run to get it. A\n * skip is never silent, because the operator's next auto-mode session is where\n * they would otherwise find out (#33).\n *\n * \"free\", never \"read-only\": see PERMISSIONS_QUESTION for why this tier cannot\n * honestly be called the latter. The line that reports a WRITE carries the\n * `doctor` pointer too, since that is the other moment an operator learns rules\n * landed without seeing them or the flag caveat that qualifies them.\n */\nfunction permissionsLine(io: Io, p: PermissionsResult): string {\n const label = paint(io, 'bold', 'Permissions:');\n if (p.added.length > 0) {\n return `${paint(io, 'green', '✓')} ${label} ${p.added.length} free tenjin commands added to ${p.path}. Full caveats: ${PERMISSIONS_DOC_URL}`;\n }\n if (p.skipped === undefined) {\n return `${paint(io, 'green', '✓')} ${label} the ${FREE_VERB_RULES.length} free tenjin commands were already allowed in ${p.path}`;\n }\n if (p.skipped === 'harness-not-claude') {\n return `${paint(io, 'dim', '-')} ${label} not wired (Claude Code only). The lines your harness needs: ${PERMISSIONS_DOC_URL}`;\n }\n if (p.skipped === 'dry-run') {\n return `${paint(io, 'dim', '-')} ${label} unchanged (dry run).`;\n }\n if (p.skipped === 'declined' || p.skipped === 'not-requested') {\n return `${paint(io, 'dim', '-')} ${label} unchanged. Allow the ${FREE_VERB_RULES.length} free tenjin commands with: tenjin install --allow-free-verbs`;\n }\n if (p.skipped === 'changed-since-read') {\n // Nothing is wrong with the file and the flag is not the remedy: another\n // writer touched it mid-run, so the merge has to be recomputed against what\n // is there now. The catch-all below says \"fix it\", which is wrong here.\n return `${paint(io, 'yellow', '!')} ${label} ${p.path} changed while it was being updated, so nothing was written. Re-run: tenjin install`;\n }\n return `${paint(io, 'yellow', '!')} ${label} ${p.path} was left untouched. Fix it, then: tenjin install --allow-free-verbs`;\n}\n\nfunction walletLine(io: Io, w: WalletOutcome): string {\n const label = paint(io, 'bold', 'Wallet:');\n if (w.status === 'existing') {\n return `${paint(io, 'green', '✓')} ${label} ${w.address} (existing). Check funds with: tenjin wallet balance`;\n }\n if (w.status === 'created') {\n return `${paint(io, 'green', '✓')} ${label} ${w.address}, holding $0. Fund it with a few dollars of USDC on Base, then: tenjin wallet balance`;\n }\n if (w.status === 'skipped') {\n const icon = w.reason === 'no-passphrase-store' || w.reason === 'create-failed' ? '!' : '-';\n const color = icon === '!' ? 'yellow' : 'dim';\n return `${paint(io, color, icon)} ${label} none (${w.reason}). ${w.fix}`;\n }\n return `${paint(io, 'dim', '-')} ${label} none. Create one later with: tenjin wallet create`;\n}\n\n/**\n * What a freshly created wallet means, at the moment it is created. Three things\n * an operator has to know and would otherwise learn the hard way: it is empty,\n * only a human can fund it, and where the key lives.\n */\nfunction walletDisclosure(w: WalletOutcome, dataDir: string): string[] {\n if (w.status !== 'created') return [];\n return [\n `A wallet was created at ${walletPath(dataDir)}: the key is encrypted at rest (keystore v3, scrypt, mode 0600) and never leaves this machine.`,\n 'It holds $0. Funding it is a human step: run `tenjin fund` (card checkout via Coinbase, opened in your browser), or send USDC on Base to that address.',\n ];\n}\n\n/** `tenjin-search, tenjin-publish (CLI); tenjin (hosted, zero-install fallback)`. */\nfunction skillRoster(h: HarnessResult): string {\n const cli = h.skills.filter((s) => s.cli).map((s) => s.name);\n const hosted = h.skills.filter((s) => !s.cli).map((s) => s.name);\n const parts: string[] = [];\n if (cli.length > 0) parts.push(`${cli.join(', ')} (CLI)`);\n if (hosted.length > 0) parts.push(`${hosted.join(', ')} (hosted, zero-install fallback)`);\n return parts.join('; ');\n}\n\n/** The single line of consequence attached to a mode, wherever it is shown. */\nfunction modeBlurb(v: PublishMode): string {\n return v === 'auto'\n ? 'Your agent publishes clean pieces on its own; your harness still shows each command for approval.'\n : v === 'review'\n ? 'Your agent asks you in chat before every publish.'\n : 'Fully unattended; only hard blocks stop it.';\n}\n\n/**\n * The wallet decision. A wallet is now created BY DEFAULT on both paths, because\n * the loop this command exists to set up does not close without one: `buy` needs\n * a funded key and publish-on-MISS needs a key to sign the write, so a walletless\n * install is a setup that stops at the first useful thing the agent tries.\n *\n * The headless path is the change. It creates without asking, using the\n * passphrase policy `resolvePassphraseForCreate` already enforces: an explicit\n * `TENJIN_WALLET_PASSPHRASE`, else a strong generated passphrase written to the\n * platform's OS credential store and verified by reading it back. When neither is\n * available it creates NOTHING and reports `skipped: no-passphrase-store` with\n * both remedies. There is deliberately no plain-file fallback: a passphrase\n * sitting next to the keystore it unlocks protects nothing, and an install is\n * never the right place to invent one.\n *\n * A creation failure never fails the install. The skills, hooks and permissions\n * this run just wired are all useful without a wallet, so the failure is reported\n * loudly and the command still succeeds.\n */\nasync function resolveWallet(\n ctx: CommandContext,\n deps: InstallDeps,\n skipReason: 'dry-run' | 'flag' | undefined,\n canPrompt: boolean,\n): Promise<WalletOutcome> {\n const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);\n if (exists) {\n return {\n status: 'existing',\n address: await (deps.walletAddress ?? existingWalletAddress)(ctx),\n };\n }\n if (skipReason !== undefined) {\n return { status: 'skipped', reason: skipReason, fix: walletFix(skipReason) };\n }\n\n // Interactive keeps the question (default yes); headless has nobody to ask and\n // takes the default rather than treating silence as a no.\n if (canPrompt) {\n const confirm = deps.confirmWallet ?? defaultConfirm;\n if (!(await confirm(WALLET_QUESTION))) return { status: 'declined' };\n }\n\n try {\n const create =\n deps.createWallet ??\n ((c: CommandContext) => defaultCreateWallet(c, deps.walletPassphrase, deps.env));\n return { status: 'created', address: await create(ctx) };\n } catch (err) {\n // The one failure with a real remedy: no env passphrase and no OS store, so\n // resolvePassphraseForCreate refused rather than encrypt with a passphrase\n // that has no durable copy. Anything else is reported as itself.\n const reason: WalletSkipReason = isNoPassphraseError(err)\n ? 'no-passphrase-store'\n : 'create-failed';\n return {\n status: 'skipped',\n reason,\n fix: walletFix(reason),\n ...(reason === 'create-failed'\n ? { warning: `The wallet could not be created: ${errorText(err)}` }\n : {}),\n };\n }\n}\n\n/** Is this the passphrase layer refusing because no durable store could serve? */\nfunction isNoPassphraseError(err: unknown): boolean {\n return (\n err instanceof CliError &&\n err.code === 'USAGE' &&\n err.message.includes('No wallet passphrase is available')\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function existingWalletAddress(ctx: CommandContext): Promise<string> {\n return (await describeWallet(resolveWalletProvider(ctx))).address;\n}\n\nasync function defaultCreateWallet(\n ctx: CommandContext,\n passphrase?: PassphraseOverrides,\n env?: NodeJS.ProcessEnv,\n): Promise<string> {\n const result = await runWalletCreate(ctx, {\n ...(passphrase !== undefined ? { passphrase } : {}),\n ...(env !== undefined ? { env } : {}),\n });\n return (result.data as { address: string }).address;\n}\n\n/** The shared confirm, defaulting to YES (setup ergonomics); cancel reads as no. */\nfunction defaultConfirm(label: string): Promise<boolean> {\n return confirmChoice(label, true);\n}\n\n/**\n * Doctor problems only. A fully green run prints nothing here: the summary is\n * the whole output, and \"everything checks out\" is what an absent warning means.\n *\n * The \"no wallet\" warn is dropped when the summary already carries it (#80): the\n * summary's own wallet line says `none` and names the same `tenjin wallet create`,\n * and someone who only wants `tenjin search` does not need it twice, in yellow,\n * for a wallet they were just told is optional. Every other wallet warn — a\n * keystore that will not open, an invalid TENJIN_WALLET_KEY, loose file\n * permissions — still prints, because nothing else in the output says it.\n *\n * Hence `isNoWalletCheck` rather than the check's NAME. `resolveWallet` probes for\n * a wallet FILE, so it reports no wallet for a machine whose credential is a\n * broken env key; matching on the name suppressed doctor's warning about it and\n * left the run silent about the only wallet state install cannot describe itself.\n *\n * `summaryAlreadySaysNoWallet` covers BOTH ways this run can end without one, and\n * both print the same `tenjin wallet create` pointer: `declined` (the operator\n * said no) and `skipped` (never asked, or the passphrase had nowhere to live).\n * `created` and `existing` never suppress, since there IS a wallet and any warn\n * about it is news.\n */\nfunction summaryAlreadySaysNoWallet(wallet: WalletOutcome): boolean {\n return wallet.status === 'declined' || wallet.status === 'skipped';\n}\n\nfunction doctorNotices(io: Io, doctor: DoctorChecks, wallet: WalletOutcome): string[] {\n const problems = doctor.checks.filter(\n (c) => c.status !== 'ok' && !(summaryAlreadySaysNoWallet(wallet) && isNoWalletCheck(c)),\n );\n if (problems.length === 0) return [];\n const lines = [paint(io, 'yellow', 'Some checks need attention:')];\n for (const c of problems) {\n const icon = c.status === 'fail' ? paint(io, 'red', '✗') : paint(io, 'yellow', '!');\n // Same seam as renderDoctorHuman: `detail`/`fix` carry server-sourced substrings.\n lines.push(` ${icon} ${c.name}: ${sanitizeForTerminal(c.detail)}`);\n if (c.fix !== undefined) {\n lines.push(paint(io, 'dim', ` fix: ${sanitizeForTerminal(c.fix)}`));\n }\n }\n return lines;\n}\n\n// --- Publish-mode selection (D38 setup) ------------------------------------------\n\n/**\n * The STORED default: what a `--dry-run` or a cancelled question leaves\n * `publish.mode` at, which is to say unset. A NON-INTERACTIVE run no longer lands\n * here; it settles RECOMMENDED_MODE below, because leaving the key unset made a\n * headless install the one path where the agent's publishing consent silently\n * differed from what the operator would have been shown. This value is now the\n * \"nobody chose anything and nothing was written\" answer only.\n */\nconst DEFAULT_MODE: PublishMode = CONFIG_DEFAULTS.publish.mode;\n\n/**\n * What a headless run settles on, and it is the SAME answer the interactive\n * select recommends (PUBLISH_MODE_CHOICES' initialValue), not the stored default.\n * That equality is the point: \"non-interactive is an interactive all-yes\" has to\n * be true of publishing too, or the sentence is wrong about the one decision\n * that governs what the agent puts on a public marketplace.\n */\nconst RECOMMENDED_MODE: PublishMode = 'auto';\n\n/** Decision 1's literal copy: one line of consequence per option, `auto` first. */\nexport const PUBLISH_MODE_CHOICES = [\n {\n value: 'auto',\n label: 'Auto (recommended)',\n hint: 'your agent publishes clean pieces on its own; your harness still shows each command for approval',\n },\n { value: 'review', label: 'Ask me in chat first' },\n { value: 'full-auto', label: 'Fully unattended', hint: 'only hard blocks stop it' },\n] as const satisfies readonly { value: PublishMode; label: string; hint?: string }[];\n\nexport const PUBLISH_MODE_QUESTION = 'When your agent has something worth publishing:';\n\n/**\n * Resolve (and, for an explicit choice, persist) the publish consent mode at\n * install time. Precedence: `--publish-mode` flag > an already-configured global\n * mode > the interactive select > the headless settle > the untouched default.\n * A cancelled select and `--dry-run` write nothing and leave `publish.mode` unset\n * so its provenance stays `default`; a non-interactive run SETTLES the\n * recommended mode, which is the one case that writes without being asked.\n */\nasync function resolvePublishMode(\n flag: PublishMode | undefined,\n ctx: CommandContext,\n deps: InstallDeps,\n dryRun: boolean,\n interactive: boolean,\n): Promise<PublishModeSelection> {\n if (flag !== undefined) {\n if (!dryRun) await persistPublishMode(ctx.dataDir, flag); // --dry-run: would-set only\n return { value: flag, source: 'flag' };\n }\n\n // Only the GLOBAL config file counts as \"already configured\" for setup: env/flag\n // are per-run and a project `.tenjin.json` is not this machine's global choice.\n const config = await loadRawConfig(ctx.dataDir);\n if (config.publish?.mode !== undefined) {\n return { value: config.publish.mode, source: 'existing' };\n }\n\n // A dry run asks nothing and writes nothing, so it reports the untouched\n // default rather than the mode a real run would settle.\n if (dryRun) return { value: DEFAULT_MODE, source: 'default-skipped' };\n\n // `interactive` is the walkthrough gate (already false under --json or off a\n // TTY), so a machine consumer never sits behind a prompt. It SETTLES the\n // recommended mode rather than leaving the key unset: every other decision this\n // command makes headlessly lands on what an interactive yes would have chosen,\n // and leaving this one alone made a headless install the only path where the\n // agent's publishing consent silently differed from the one the operator was\n // shown. An already-configured mode was returned above, so this only ever\n // writes where nothing was set.\n if (!interactive) {\n await persistPublishMode(ctx.dataDir, RECOMMENDED_MODE);\n return { value: RECOMMENDED_MODE, source: 'headless-default' };\n }\n\n const answer = await (deps.promptPublishMode ?? defaultPromptPublishMode)();\n if (answer === null) return { value: DEFAULT_MODE, source: 'default-skipped' }; // cancelled: no write\n // The seam is injectable, so an answer is validated rather than trusted; an\n // unparseable one is a cancel, not a write of something unknown.\n const parsed = PublishModeSchema.safeParse(answer);\n if (!parsed.success) return { value: DEFAULT_MODE, source: 'default-skipped' };\n await persistPublishMode(ctx.dataDir, parsed.data);\n return { value: parsed.data, source: 'prompt' };\n}\n\nfunction defaultPromptPublishMode(): Promise<PublishMode | null> {\n return selectOne<PublishMode>({\n message: PUBLISH_MODE_QUESTION,\n choices: PUBLISH_MODE_CHOICES.map((c) => ({ ...c })),\n initialValue: 'auto',\n });\n}\n\nfunction parseModeFlag(value: string): PublishMode {\n return parsePublishModeFlag(value, '--publish-mode');\n}\n\n// --- Harness permissions (decision 2) ---------------------------------------------\n\n/**\n * Decision 2's literal copy: one question, and a consequence that lib/permissions.ts\n * would agree with. NOT \"read-only\" and NOT \"never touches your wallet\" — that\n * module refuses both claims in as many words (`search` and `outcome` POST\n * off-machine, `read` saves to the library and can present a cached\n * wallet-derived delegation, and two of the nine rules are `wallet show` /\n * `wallet balance`). What is actually true of the whole tier is that it cannot\n * spend and cannot move your keys, so that is what the question says.\n *\n * The pointer is how FLAG_CAVEAT reaches the consent moment: the walkthrough\n * prints neither the rules nor the flag caveat, so the yes/no that replaced them\n * names where both live in full. It used to point at `tenjin doctor`, which\n * printed them; doctor now points at the same page (#81).\n */\nexport const PERMISSIONS_QUESTION = [\n 'Let your agent search tenjin without permission popups?',\n `Adds ${FREE_VERB_RULES.length} free commands to ~/.claude/settings.json.`,\n 'None can spend USDC or move your keys; doctor may check your wallet still opens.',\n 'Three send or store data (search, outcome, read).',\n `Full caveats: ${PERMISSIONS_DOC_URL}`,\n].join(' ');\n\n/** The wallet decision's literal copy. */\nexport const WALLET_QUESTION = 'Create a wallet now?';\n\n/**\n * Settle the harness allowlist. The write itself is free-verb only and cannot\n * widen (see lib/harness-permissions.ts); this decides ONLY whether to call it.\n *\n * Precedence: `--no-allow-free-verbs` refuses outright, `--allow-free-verbs`\n * wires it, an interactive run asks, and a NON-INTERACTIVE run wires it. That\n * last arm is the change #33 was really asking for: the machine most likely to be\n * denied mid-task is the headless one, and leaving it unwired because nobody was\n * there to say yes made a bare `tenjin install` produce an install that does not\n * work. The disclosure and the undo ride the output on both paths.\n *\n * The probe runs on EVERY path that might write, including the headless ones.\n * Nothing left to grant is not a question and not a write: it is the ordinary\n * state of a re-run, and returning the SNAPSHOT's own result is what makes a\n * re-run report `alreadyPresent` accurately instead of an empty pair. It also\n * keeps the consent gate honest, because calling the writer after a zero-pending\n * probe would re-read the file and silently re-add a rule revoked in between. An\n * unreadable file is \"unknown\", never \"already allowed\", so it falls through.\n */\nasync function resolvePermissions(args: {\n plans: HarnessPlan[];\n home: string;\n deps: InstallDeps;\n flag: boolean | undefined;\n dryRun: boolean;\n canPrompt: boolean;\n}): Promise<PermissionsResult> {\n const { plans, home, deps, flag, dryRun, canPrompt } = args;\n // Only Claude Code has a settings file with this shape. Codex and the shared\n // Agent Skills location gate permissions elsewhere, so there is nothing here to\n // write for them, and guessing at another harness's config would be the kind of\n // uninvited write this whole module is careful about.\n if (!plans.some((p) => p.harness === 'claude')) {\n return permissionsSkipped(plans[0]?.harness ?? 'shared', home, 'harness-not-claude');\n }\n if (dryRun) return permissionsSkipped('claude', home, 'dry-run');\n if (flag === false) return permissionsSkipped('claude', home, 'declined');\n\n const probe = await (deps.inspectPermissions ?? inspectFreeVerbRules)(home);\n if (probe.satisfied !== undefined) return probe.satisfied;\n // Nothing to GRANT, but something of ours to retract: an older version's rule\n // for a command that no longer exists. That needs no consent — it only ever\n // removes a rule this CLI wrote — so it runs without the prompt.\n if (probe.pending !== null && probe.pending.length === 0) return wireFreeVerbAllowlist(home);\n\n if (flag === true || !canPrompt) return wireFreeVerbAllowlist(home);\n\n const confirm = deps.confirmPermissions ?? defaultConfirm;\n if (!(await confirm(PERMISSIONS_QUESTION))) {\n return permissionsSkipped('claude', home, 'declined');\n }\n return wireFreeVerbAllowlist(home);\n}\n\n// --- Search hooks (decision 3) ----------------------------------------------------\n\n/**\n * The search-hook question's literal copy. It names both hooks, because they are\n * installed together and the second one is the surprising half: an operator who\n * agreed to \"check Tenjin before a web search\" has not thereby agreed to a\n * reminder at the end of every turn, so the question says both out loud.\n */\nexport const SEARCH_HOOKS_QUESTION =\n 'Let Tenjin ride along with your web searches? (Escape skips, registering nothing)';\n\nexport const SEARCH_HOOKS_CHOICES = [\n {\n value: 'auto',\n label: 'Yes, check Tenjin first (recommended)',\n hint: 'before a WebSearch, ask tenjin.blog the same question (free, anonymous, 2s budget) and mention a tested answer; the query text leaves the machine',\n },\n {\n value: 'remind',\n label: 'Just remind me',\n hint: 'a one-line reminder, nothing sent off-machine',\n },\n { value: 'off', label: 'No hooks', hint: 'nothing is registered' },\n] as const satisfies readonly { value: SearchHookMode; label: string; hint?: string }[];\n\n/**\n * Settle the harness hooks. Same shape as the allowlist decision and the same\n * default posture: a flag settles it, an interactive run asks, and a\n * non-interactive run wires `auto` with the disclosure and undo in its output.\n *\n * The chosen mode is PERSISTED to config, so it is the script's behavior from\n * then on and `tenjin config set hooks.searchMode` is enough to change it later\n * without re-installing. A `--dry-run` persists nothing, like the publish mode.\n */\nasync function resolveHooks(args: {\n plans: HarnessPlan[];\n home: string;\n ctx: CommandContext;\n deps: InstallDeps;\n flag: SearchHookMode | undefined;\n noHooks: boolean;\n dryRun: boolean;\n canPrompt: boolean;\n}): Promise<HooksResult> {\n const { plans, home, ctx, deps, flag, noHooks, dryRun, canPrompt } = args;\n const dataDir = ctx.dataDir;\n const stored = (await loadRawConfig(dataDir)).hooks?.searchMode;\n\n if (!plans.some((p) => p.harness === 'claude')) {\n const harness = plans[0]?.harness ?? 'shared';\n return hooksSkipped(\n harness,\n home,\n dataDir,\n flag ?? stored ?? DEFAULT_HOOK_MODE,\n 'harness-not-claude',\n );\n }\n // `--no-hooks` is a decision about THIS RUN and writes no config, so the stored\n // mode is reported unchanged and a later bare re-run wires them. That is the\n // difference from `--search-hooks off`, which is a durable statement.\n if (noHooks) {\n return hooksSkipped('claude', home, dataDir, stored ?? DEFAULT_HOOK_MODE, 'declined');\n }\n\n const mode = await chooseHookMode(flag, stored, deps, dryRun, canPrompt);\n // Cancelling the select is a decision NOT to decide, so it behaves exactly like\n // `--no-hooks`: nothing registered, nothing written. Every other decision in\n // this walkthrough already treats Escape that way, and this one used to be the\n // single prompt where backing out still wired and persisted a mode.\n if (mode === null) {\n return hooksSkipped('claude', home, dataDir, stored ?? DEFAULT_HOOK_MODE, 'declined');\n }\n if (dryRun) return hooksSkipped('claude', home, dataDir, mode, 'dry-run');\n if (mode !== (stored ?? DEFAULT_HOOK_MODE) || stored === undefined) {\n await persistSearchHookMode(dataDir, mode);\n }\n // `off` is a decision not to register anything, so settings.json is not touched\n // at all. It is NOT the same as an inert script: an operator who later sets the\n // mode back to `auto` re-runs install, which is what the fix string says.\n if (mode === 'off') return hooksSkipped('claude', home, dataDir, mode, 'mode-off');\n return wireSearchHooks({ homeDir: home, dataDir, mode });\n}\n\n/** The stored default for a run that was never asked. */\nconst DEFAULT_HOOK_MODE: SearchHookMode = CONFIG_DEFAULTS.hooks.searchMode;\n\n/**\n * Precedence for the hook mode: `--search-hooks` > the interactive select > an\n * already-configured mode > the default.\n *\n * NULL means the operator cancelled (Escape, ctrl-C, or an answer the schema does\n * not recognize). That is not a mode and must not be resolved into one: the\n * caller treats it as `--no-hooks` for this run, registering nothing and writing\n * no config, which is what every other cancel in this walkthrough does.\n */\nasync function chooseHookMode(\n flag: SearchHookMode | undefined,\n stored: SearchHookMode | undefined,\n deps: InstallDeps,\n dryRun: boolean,\n canPrompt: boolean,\n): Promise<SearchHookMode | null> {\n if (flag !== undefined) return flag;\n if (dryRun || !canPrompt) return stored ?? DEFAULT_HOOK_MODE;\n const answer = await (deps.promptSearchHooks ?? defaultPromptSearchHooks)();\n if (answer === null) return null;\n // The seam is injectable, so an answer is validated rather than trusted; an\n // unrecognized one is a cancel, not a write of something unknown.\n const parsed = SearchHookModeSchema.safeParse(answer);\n return parsed.success ? parsed.data : null;\n}\n\nfunction defaultPromptSearchHooks(): Promise<SearchHookMode | null> {\n return selectOne<SearchHookMode>({\n message: SEARCH_HOOKS_QUESTION,\n choices: SEARCH_HOOKS_CHOICES.map((c) => ({ ...c })),\n initialValue: 'auto',\n });\n}\n\n// --- Detection + planning --------------------------------------------------------\n\ninterface HarnessPlan {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n wiresAgentsMd: boolean;\n home: string;\n}\n\n/**\n * Turn detection (or an explicit --harness override) into the ordered, de-duped\n * list of targets to write. Codex and the shared fallback both land in\n * ~/.agents/skills (the harness-shared Agent Skills location), so a request for\n * both collapses to one target keyed by that directory.\n */\nfunction resolvePlans(\n override: string[] | undefined,\n home: string,\n which: (bin: string) => boolean,\n): HarnessPlan[] {\n if (override !== undefined && override.length > 0) {\n const plans = override.map((v) => planFor(validateHarness(v), ['override'], true, home));\n return dedupeBySkillsDir(plans);\n }\n\n const plans: HarnessPlan[] = [];\n // Same two probes doctor's skills check gates its per-directory verdicts on.\n const claudeBy = harnessDetectedBy(home, 'claude', which);\n const codexBy = harnessDetectedBy(home, 'codex', which);\n if (claudeBy.length > 0) plans.push(planFor('claude', claudeBy, true, home));\n if (codexBy.length > 0) plans.push(planFor('codex', codexBy, true, home));\n if (plans.length === 0) {\n // Nothing detected: the shared Agent Skills location is the fallback target, so\n // a harness installed later still finds the skills.\n plans.push(planFor('shared', ['fallback'], false, home));\n }\n return dedupeBySkillsDir(plans);\n}\n\nfunction planFor(\n harness: Harness,\n detectedBy: string[],\n detected: boolean,\n home: string,\n): HarnessPlan {\n const skillsDir = harnessTargetDir(home, harness);\n return { harness, detected, detectedBy, skillsDir, wiresAgentsMd: harness !== 'claude', home };\n}\n\nfunction dedupeBySkillsDir(plans: HarnessPlan[]): HarnessPlan[] {\n const seen = new Set<string>();\n const out: HarnessPlan[] = [];\n for (const p of plans) {\n if (seen.has(p.skillsDir)) continue;\n seen.add(p.skillsDir);\n out.push(p);\n }\n return out;\n}\n\nfunction validateHarness(value: string): Harness {\n if ((HARNESSES as readonly string[]).includes(value)) return value as Harness;\n throw new CliError('USAGE', `Unknown harness \"${value}\"`, {\n fix: `--harness must be one of: ${HARNESSES.join(', ')}.`,\n });\n}\n\n// --- Applying a plan -------------------------------------------------------------\n\n/**\n * Wire one harness target. EVERY packaged skill is written on every run,\n * unconditionally: an existing Tenjin skill in the target (typically the hosted\n * zero-install one from tenjin.blog/skills.md) is never a reason to skip, because\n * install on such a machine is the UPGRADE path (#35). The hosted mirror is kept\n * and refreshed rather than removed (roadmap G4: it is the permanent zero-install\n * curriculum); the two CLI adapter skills land beside it and supersede it while\n * the CLI is present.\n */\nasync function applyPlan(\n plan: HarnessPlan,\n skillsSource: string,\n dryRun: boolean,\n): Promise<HarnessResult> {\n const skills: SkillResult[] = [];\n const warnings: string[] = [];\n for (const name of SKILL_NAMES) {\n const { status, warning, preexisting } = await installSkill(\n join(skillsSource, name),\n join(plan.skillsDir, name),\n dryRun,\n name,\n );\n skills.push({\n name,\n status,\n preexisting,\n cli: (CLI_SKILL_NAMES as readonly string[]).includes(name),\n modelInvocable: await landedInvocable(plan.skillsDir, skillsSource, name, dryRun),\n });\n if (warning !== undefined) warnings.push(warning);\n }\n\n const hostedPreexisting = skills.some((s) => s.name === HOSTED_SKILL_NAME && s.preexisting);\n // The notice is about arriving through the hosted skill, which is only news when\n // the CLI adapters were NOT already wired: after an earlier install the mirror on\n // disk is one we wrote, and announcing it is the CLI reporting its own footprint.\n const hostedArrivedFirst = hostedPreexisting && !skills.some((s) => s.cli && s.preexisting);\n const result: HarnessResult = {\n harness: plan.harness,\n detected: plan.detected,\n detectedBy: plan.detectedBy,\n skillsDir: plan.skillsDir,\n skills,\n hostedPreexisting,\n hostedArrivedFirst,\n notes: notesFor(plan, hostedArrivedFirst),\n warnings,\n };\n\n if (plan.wiresAgentsMd) result.codexNetworkRule = CODEX_NETWORK_RULE;\n return result;\n}\n\nfunction notesFor(plan: HarnessPlan, hostedArrivedFirst: boolean): string[] {\n const notes =\n plan.harness === 'claude'\n ? [\n 'Installed at the user level (~/.claude/skills). A Claude Code plugin will later make this automatic.',\n ]\n : [\n 'Copied into the shared Agent Skills location (~/.agents/skills). Codex and any Agent-Skills-compatible harness read it there.',\n ];\n if (hostedArrivedFirst) {\n // \"The skill stays\", never \"your copy is untouched\": the FILE is replaced by\n // this package's mirror, and a note reading as preservation beside a warning\n // saying replacement is worse than either alone.\n notes.push(\n `The hosted ${HOSTED_SKILL_NAME} skill was already here; the skill stays as the zero-install fallback (its file is replaced by this package's mirror) and the CLI skills (${CLI_SKILL_NAMES.join(', ')}) take precedence while the CLI is installed.`,\n );\n }\n return notes;\n}\n\n/**\n * Did the skill actually land model-invocable? Read back from the target so the\n * reported value is the file a harness will read, not what we intended to write.\n * A dry run wrote nothing, so it READS THE PACKAGED SOURCE — the file that would\n * land. Hardcoding `true` there was wrong for the one skill whose value can\n * legitimately be false: `assertSkillsSource` exempts the hosted mirror from the\n * invocability assertion, so a shadowed mirror ships and must report as shadowed on\n * both paths.\n */\nasync function landedInvocable(\n skillsDir: string,\n skillsSource: string,\n name: string,\n dryRun: boolean,\n): Promise<boolean> {\n // Guarded like every other read of this path. It is read back AFTER the write, so\n // an external writer can have swapped it for a pipe or a device in between, and a\n // raw read there would hang the command that just finished its work.\n const read = await readSkillFile(join(dryRun ? skillsSource : skillsDir, name, 'SKILL.md'));\n if (read.kind !== 'ok') return false;\n return !isModelInvocationDisabled(read.bytes.toString('utf8'));\n}\n\n/**\n * Every packaged skill landed in every target. Runs after ALL targets are written,\n * never mid-loop: a throw between two targets would leave target 1 rewritten and\n * target 2 untouched. (It still sits ahead of the doctor run, the publish-mode\n * question and the wallet step, so a throw here skips those either way.)\n *\n * Presence only. Whether a skill is model-invocable is a property of the PACKAGED\n * source, checked up front by `assertSkillsSource` before anything is written.\n */\nasync function assertSkillsLanded(plans: HarnessPlan[], dryRun: boolean): Promise<void> {\n if (dryRun) return;\n const missing: string[] = [];\n for (const plan of plans) {\n for (const name of SKILL_NAMES) {\n if (!existsSync(join(plan.skillsDir, name, 'SKILL.md'))) {\n missing.push(join(plan.skillsDir, name));\n }\n }\n }\n if (missing.length === 0) return;\n throw new CliError('INTERNAL', `Skills were not written: ${missing.join(', ')}`, {\n // Safe to point at permissions because nothing removes a landed file any more:\n // each shipped file arrives by its own atomic rename. When this was a\n // rm-then-write it also fired on a lost race, and sent people to chmod a\n // directory that was fine.\n fix: `Check that you can write to the skills directory (\\`ls -ld ${dirname(missing[0] ?? '')}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n// --- Human rendering -------------------------------------------------------------\n\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });\n return styleText(format, text);\n}\n\n// --- Skills source guard ---------------------------------------------------------\n\n/**\n * Guard the packaged source BEFORE any target is touched, so a bad package aborts\n * with nothing written rather than mid-copy.\n *\n * The model-invocable assertion covers only CLI_SKILL_NAMES. The hosted `tenjin`\n * mirror is written verbatim from tenjin.blog/skills.md by scripts/sync-skill.mjs\n * and its frontmatter is not authored here: if upstream ever adds\n * `disable-model-invocation: true` (a plausible way to say \"prefer the CLI\n * skills\"), asserting on it would hard-fail every install with a fix that cannot\n * work, and skill-drift.yml would stay green because the mirror still matches\n * upstream. Doctor warns about the mirror instead.\n */\nasync function assertSkillsSource(dir: string): Promise<void> {\n for (const name of SKILL_NAMES) {\n if (!existsSync(join(dir, name, 'SKILL.md'))) {\n throw new CliError('INTERNAL', `Packaged skill \"${name}\" is missing under ${dir}`, {\n fix: 'Reinstall tenjin-cli; the published package must ship every skill under skills/.',\n });\n }\n }\n for (const name of CLI_SKILL_NAMES) {\n const text = await readFile(join(dir, name, 'SKILL.md'), 'utf8');\n if (isModelInvocationDisabled(text)) {\n throw new CliError(\n 'INTERNAL',\n `Packaged skill \"${name}\" carries disable-model-invocation: true, so no harness would surface it`,\n {\n fix: 'Reinstall tenjin-cli; the published CLI skills must be model-invocable.',\n },\n );\n }\n }\n}\n","import { lstat, readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { claudeSettingsPath } from './harness-permissions';\nimport { hooksDir } from './paths';\nimport {\n STOP_HOOK_FILE,\n WEBSEARCH_HOOK_FILE,\n stopHookScript,\n websearchHookScript,\n} from './hook-scripts';\nimport type { SearchHookMode } from './config';\n\n/**\n * The second place the CLI writes into a harness's own settings file, and it\n * carries the same invariants as lib/harness-permissions.ts for the same reasons:\n * additive only, never clobbers a file it cannot understand, and refuses rather\n * than overwriting a change that landed mid-run. Read that module's header first;\n * what follows is only what is different here.\n *\n * WHAT A HOOK ENTRY IS. Unlike a permission rule, a hook entry names an\n * executable. Two properties keep that honest:\n *\n * - The command can only ever be `node <path under the Tenjin data dir>`. There\n * is no argument, no config key, and no call path that lets a caller point a\n * hook at some other program, and the scripts themselves are generated from\n * constants in lib/hook-scripts.ts rather than from anything on the wire.\n * - Neither hook can block, deny, or modify a tool call. The WebSearch hook emits\n * `additionalContext` and never `permissionDecision`, so a WebSearch always\n * proceeds; the Stop hook only ever adds a line at the end of a turn.\n *\n * OWNERSHIP IS BY PATH. An entry is ours when its command mentions one of our two\n * script filenames. That is what makes a re-install idempotent, lets a drifted\n * command (an older install's path, a moved data dir) be rewritten in place\n * instead of duplicated, and keeps every entry someone else wrote untouched.\n */\n\n/** The hook events this module writes, in the order they are reported. */\nexport const HOOK_EVENTS = ['PreToolUse', 'Stop'] as const;\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** The tool the WebSearch hook fires on. Never `WebFetch`, never a wildcard. */\nexport const WEBSEARCH_MATCHER = 'WebSearch';\n\n/**\n * Seconds the harness allows each hook before killing it, and the HARD bound on\n * how long either can delay anything. The scripts' own watchdogs (2s and 1.5s)\n * are the design budget and cover the ordinary case, but they are event-loop\n * timers: a synchronous read that blocks outlasts them. This kill does not, so it\n * is the number to quote when the question is \"what is the worst case\".\n */\nconst HOOK_TIMEOUT_SECONDS = 5;\n\nexport type HooksSkipReason =\n | 'harness-not-claude'\n | 'mode-off'\n | 'declined'\n | 'dry-run'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\nexport interface HooksResult {\n /** The harness this outcome is about; only `claude` has a settings file we write. */\n harness: string;\n /** The settings file, absent when the harness has no such file. */\n path?: string;\n /** Where the hook scripts live (or would). */\n scriptsDir: string;\n /** The behavior the installed scripts will follow (config `hooks.searchMode`). */\n mode: SearchHookMode;\n /** Events whose entry this run appended. */\n added: HookEvent[];\n /** Events whose entry was already there, byte-identical. */\n alreadyPresent: HookEvent[];\n /** Events whose existing entry pointed somewhere else and was rewritten in place. */\n updated: HookEvent[];\n /** Script files this run wrote or refreshed. */\n scripts: string[];\n skipped?: HooksSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n}\n\n/** The undo, stated the same way everywhere it is shown. */\nexport function hooksUndo(settingsPath: string, scriptsDir: string): string {\n return `Undo anytime: \\`tenjin config set hooks.searchMode off\\` disarms them, or delete the tenjin hook entries from ${settingsPath} and the scripts in ${scriptsDir}.`;\n}\n\nfunction skip(\n reason: HooksSkipReason,\n args: {\n harness: string;\n path?: string;\n scriptsDir: string;\n mode: SearchHookMode;\n warning?: string;\n fix?: string;\n },\n): HooksResult {\n return {\n harness: args.harness,\n ...(args.path !== undefined ? { path: args.path } : {}),\n scriptsDir: args.scriptsDir,\n mode: args.mode,\n added: [],\n alreadyPresent: [],\n updated: [],\n scripts: [],\n skipped: reason,\n ...(args.warning !== undefined ? { warning: args.warning } : {}),\n ...(args.fix !== undefined ? { fix: args.fix } : {}),\n };\n}\n\n/** A decision NOT to wire, shaped like a write outcome so the caller has one type. */\nexport function hooksSkipped(\n harness: string,\n homeDir: string,\n dataDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n): HooksResult {\n return skip(reason, {\n harness,\n ...(harness === 'claude' ? { path: claudeSettingsPath(homeDir) } : {}),\n scriptsDir: hooksDir(dataDir),\n mode,\n fix: fixFor(reason),\n });\n}\n\n/**\n * The command that turns a skip into a write. Every skipped state names one, so a\n * machine consumer reading the envelope never has to work out the remedy from\n * prose, which is the same contract a CliError's `fix` carries.\n */\nfunction fixFor(reason: HooksSkipReason): string {\n switch (reason) {\n case 'harness-not-claude':\n return 'Hooks are wired for Claude Code only. Re-run `tenjin install --harness claude` on a machine with Claude Code.';\n case 'mode-off':\n return 'Enable them with `tenjin config set hooks.searchMode auto`, then re-run `tenjin install`.';\n case 'declined':\n case 'dry-run':\n return 'Wire them with `tenjin install --search-hooks auto`.';\n case 'changed-since-read':\n return 'Another process changed the file mid-run; re-run `tenjin install`.';\n default:\n return 'Fix the reported file, then re-run `tenjin install --search-hooks auto`.';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Quote a path for the shell the harness runs a `command` hook through. POSIX\n * shells take single quotes (with the standard `'\\''` escape for an embedded\n * one); cmd.exe does not understand them at all and takes double quotes. Getting\n * this wrong on a home directory with a space silently installs a hook that can\n * never run, so it is a real branch rather than an assumption about paths.\n */\nexport function quoteForShell(path: string, platform: string = process.platform): string {\n if (platform === 'win32') return `\"${path}\"`;\n return `'${path.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction commandFor(scriptPath: string, platform?: string): string {\n return `node ${quoteForShell(scriptPath, platform)}`;\n}\n\n/** One hook handler, exactly as it is written into settings.json. */\nfunction handlerFor(scriptPath: string, platform?: string): Record<string, unknown> {\n return {\n type: 'command',\n command: commandFor(scriptPath, platform),\n timeout: HOOK_TIMEOUT_SECONDS,\n };\n}\n\n/** Is this settings.json entry one of ours? Keyed on the script FILENAME, so a\n * data dir that moved is recognized as our entry and rewritten, not duplicated. */\nfunction ownsEntry(entry: unknown, scriptFile: string): boolean {\n if (!isPlainObject(entry)) return false;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return false;\n return handlers.some(\n (h) => isPlainObject(h) && typeof h.command === 'string' && h.command.includes(scriptFile),\n );\n}\n\ninterface HookSpec {\n event: HookEvent;\n scriptFile: string;\n script: string;\n /** Absent for Stop, which the harness fires on every occurrence with no matcher. */\n matcher?: string;\n}\n\nfunction specs(dataDir: string): HookSpec[] {\n return [\n {\n event: 'PreToolUse',\n scriptFile: WEBSEARCH_HOOK_FILE,\n script: websearchHookScript(dataDir),\n matcher: WEBSEARCH_MATCHER,\n },\n { event: 'Stop', scriptFile: STOP_HOOK_FILE, script: stopHookScript(dataDir) },\n ];\n}\n\nexport interface WireHooksOptions {\n homeDir: string;\n dataDir: string;\n mode: SearchHookMode;\n /** Shell-quoting target; injected so both branches are testable on one machine. */\n platform?: string;\n}\n\n/**\n * Write the hook scripts and merge their entries into ~/.claude/settings.json.\n *\n * The SCRIPTS are written whatever the mode, including `off`: the mode is read by\n * the script at run time, so an operator who later flips `hooks.searchMode` back\n * to `auto` gets working hooks without re-installing. Only `mode: 'off'` is\n * refused at the caller (see `hooksSkipped`), which leaves settings.json alone\n * entirely.\n *\n * Idempotent: a second run rewrites no script whose bytes match, appends no entry\n * that is already there, and does not touch settings.json at all when nothing\n * changed.\n */\nexport async function wireSearchHooks(opts: WireHooksOptions): Promise<HooksResult> {\n const { homeDir, dataDir, mode, platform } = opts;\n const scriptsDir = hooksDir(dataDir);\n const plan = specs(dataDir);\n\n const found = await inspectSettings(homeDir, scriptsDir, mode);\n if ('result' in found) return found.result;\n const { path, raw, settings, hooks } = found;\n\n const added: HookEvent[] = [];\n const alreadyPresent: HookEvent[] = [];\n const updated: HookEvent[] = [];\n const nextHooks: Record<string, unknown> = { ...hooks };\n\n for (const spec of plan) {\n const existing = hooks[spec.event];\n if (existing !== undefined && !Array.isArray(existing)) {\n return refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks.${spec.event}\" key that is not an array; it was left exactly as it is.`,\n );\n }\n const list: unknown[] = existing ?? [];\n const desired = {\n ...(spec.matcher !== undefined ? { matcher: spec.matcher } : {}),\n hooks: [handlerFor(join(scriptsDir, spec.scriptFile), platform)],\n };\n const idx = list.findIndex((e) => ownsEntry(e, spec.scriptFile));\n if (idx === -1) {\n nextHooks[spec.event] = [...list, desired];\n added.push(spec.event);\n continue;\n }\n if (JSON.stringify(list[idx]) === JSON.stringify(desired)) {\n alreadyPresent.push(spec.event);\n continue;\n }\n // Ours, but stale: an older install's path, or a data dir that moved. Rewritten\n // IN PLACE so the entry keeps its position among whatever else is registered.\n nextHooks[spec.event] = list.map((e, i) => (i === idx ? desired : e));\n updated.push(spec.event);\n }\n\n // Nothing to register: no guard is involved, so the scripts are simply brought\n // up to date. This is the path a re-run takes after an upgrade changed a body.\n if (added.length === 0 && updated.length === 0) {\n const scripts = await writeScripts(plan, scriptsDir);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n }\n\n const next = { ...settings, hooks: nextHooks };\n // TWO compares, and both are load-bearing.\n //\n // The FIRST is cheap and early: it refuses before a single byte is written, so\n // the ordinary contended case costs nothing and leaves nothing half-done.\n const changed = async (): Promise<boolean> =>\n (await readFile(path, 'utf8').catch(() => null)) !== raw;\n if (await changed()) return refuseChanged(path, scriptsDir, mode, []);\n\n // Past the first guard, and still before the entry that points at them, so a\n // harness never reads an entry naming a file that is not on disk yet.\n const scripts = await writeScripts(plan, scriptsDir);\n\n // The SECOND compare sits ADJACENT to the commit, because the writes above are\n // two read/write/rename sequences wide and this is a whole-file replacement\n // built from a snapshot taken before them. Claude Code writing settings.json\n // during that window passed the first compare and would be erased here. The\n // refusal reports the scripts that WERE refreshed, so the result describes what\n // actually happened rather than claiming nothing was touched: the bodies are\n // versioned and idempotent, so a refreshed script with no new entry is inert\n // and the re-run the fix names simply registers it.\n if (await changed()) return refuseChanged(path, scriptsDir, mode, scripts);\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n}\n\n/**\n * The `changed-since-read` refusal, carrying whatever scripts the run had already\n * refreshed. Nothing about settings.json is written on this path.\n */\nfunction refuseChanged(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n scripts: string[],\n): HooksResult {\n return {\n ...refuse(\n path,\n scriptsDir,\n mode,\n 'changed-since-read',\n `${path} changed while it was being updated, so no hooks were registered. Re-run \\`tenjin install\\`.`,\n ),\n scripts,\n };\n}\n\n/** Bring each script up to date, returning the ones this run actually wrote. A\n * body that already matches is left alone, so a re-run rewrites nothing. */\nasync function writeScripts(plan: HookSpec[], scriptsDir: string): Promise<string[]> {\n const written: string[] = [];\n for (const spec of plan) {\n const target = join(scriptsDir, spec.scriptFile);\n const onDisk = await readFile(target, 'utf8').catch(() => null);\n if (onDisk === spec.script) continue;\n await writeFileAtomic(target, spec.script, { mode: 0o755, dirMode: 0o700 });\n written.push(target);\n }\n return written;\n}\n\nfunction refuse(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n warning: string,\n): HooksResult {\n return skip(reason, { harness: 'claude', path, scriptsDir, mode, warning, fix: fixFor(reason) });\n}\n\ninterface SettingsInspection {\n path: string;\n /** The exact bytes read, so the commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n hooks: Record<string, unknown>;\n}\n\n/**\n * Resolve and read the settings file. Every refusal lives here, so the shape\n * checks and the write agree by construction. Symlinks are resolved before the\n * write for the same reason lib/harness-permissions.ts resolves them: committing\n * with a rename over a dotfiles-managed link would sever it.\n */\nasync function inspectSettings(\n homeDir: string,\n scriptsDir: string,\n mode: SearchHookMode,\n): Promise<SettingsInspection | { result: HooksResult }> {\n const declaredPath = claudeSettingsPath(homeDir);\n const entry = await lstat(declaredPath).catch(() => null);\n\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return {\n result: refuse(\n declaredPath,\n scriptsDir,\n mode,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); no hooks were registered.`,\n ),\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n if (!isPlainObject(parsed)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} is not a JSON object; it was left exactly as it is.`,\n ),\n };\n }\n settings = parsed;\n }\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isPlainObject(hooksValue)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks\" key that is not an object; it was left exactly as it is.`,\n ),\n };\n }\n return { path, raw, settings, hooks: hooksValue ?? {} };\n}\n","import type { Readable, Writable } from 'node:stream';\n\n/**\n * The pretty-prompt renderer behind the install walkthrough's seams.\n *\n * @clack/prompts is a devDependency BUNDLED by tsup (published `dependencies`\n * stays `{}`), and every entry point here is behind a dynamic `import()` so it\n * lands in its own split chunk: a `search` or `doctor` run never parses it.\n *\n * Nothing in this module is reachable from a machine run. Commands call it only\n * on the real interactive path (a TTY on both stdout and stdin, no `--json`),\n * and always through an injectable seam, so unit tests supply answers directly\n * and never touch clack or a terminal.\n *\n * Prompts render on STDERR, like every other prompt in this CLI: stdout carries\n * the human walkthrough (or a single JSON envelope) and must not be interleaved\n * with prompt chrome.\n */\n\n/** Cancel (ctrl-C, escape) is not an answer. Callers map `null` to their own default. */\nexport type Cancelled = null;\n\nexport interface SelectChoice<T extends string> {\n value: T;\n label: string;\n /** The one line of consequence shown beside the label. */\n hint?: string;\n}\n\n/** Streams a prompt reads and draws on. Injected by tests; defaults to the real ones. */\ninterface PromptStreams {\n input?: Readable;\n output?: Writable;\n}\n\n/** DECTCUM show-cursor. Written on the EOF path in case the prompt did not get to. */\nconst SHOW_CURSOR = '\\x1b[?25h';\n\n/**\n * Settle a prompt when its input goes away instead of hanging forever.\n *\n * Ctrl-D at a clack prompt leaves its promise unsettled: no resolve, no reject,\n * no cancel symbol. The process then dies on an unsettled top-level await with\n * exit 13, nothing printed, and the cursor still hidden. The readline seam this\n * replaced handled it on purpose (\"ctrl-D mid-prompt reads as the default\"), and\n * that behavior has to survive the renderer swap.\n *\n * \"Input goes away\" is two different events, and only covering one of them was\n * the original bug:\n *\n * - The STREAM ends. A pipe closes, a harness detaches, stdin was already at\n * EOF. Caught via `end` / `close`.\n * - The ctrl-D BYTE (0x04) arrives with the stream still open. This is what a\n * real terminal sends, and it is the common case. A prompt puts stdin in raw\n * mode, where 0x04 is ordinary data rather than EOF, so no stream event ever\n * fires; clack has no binding for it and simply keeps waiting. Caught via the\n * `keypress` decoder readline installs, which is a read-only view of the same\n * bytes: listening there takes nothing away from the prompt, where a `data`\n * listener would risk flipping the stream to flowing before clack reads it.\n *\n * Two mechanisms settle it, because one of them is advisory. The AbortSignal is\n * clack's own teardown: it flips the prompt to `cancel`, which restores the\n * cursor and raw mode and resolves with the cancel symbol. The race is the\n * guarantee, for a prompt that is not yet listening or never settles anyway; on\n * that path we restore the cursor ourselves, since no prompt did.\n */\nfunction withInputEnd<T>(\n streams: Required<PromptStreams>,\n onEnd: T,\n run: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n let settleEnd: (() => void) | undefined;\n const ended = new Promise<T>((resolve) => {\n settleEnd = () => {\n streams.output.write(SHOW_CURSOR);\n resolve(onEnd);\n };\n });\n\n const end = (): void => {\n controller.abort();\n settleEnd?.();\n };\n const onKeypress = (_text: string | undefined, key?: { name?: string; ctrl?: boolean }): void => {\n if (key?.ctrl === true && key.name === 'd') end();\n };\n\n streams.input.on('keypress', onKeypress);\n // A stream that finished before we got here never emits `end` again, so ask.\n if (streams.input.readableEnded) {\n queueMicrotask(end);\n } else {\n streams.input.once('end', end);\n streams.input.once('close', end);\n }\n\n return Promise.race([run(controller.signal), ended]).finally(() => {\n streams.input.off('keypress', onKeypress);\n streams.input.off('end', end);\n streams.input.off('close', end);\n });\n}\n\nfunction resolveStreams(streams: PromptStreams): Required<PromptStreams> {\n return { input: streams.input ?? process.stdin, output: streams.output ?? process.stderr };\n}\n\n/**\n * A single-choice list. Returns the chosen value, or `null` when the operator\n * cancelled or the input ended, both of which callers treat as \"leave everything\n * as it was\".\n */\nexport async function selectOne<T extends string>(opts: {\n message: string;\n choices: readonly SelectChoice<T>[];\n initialValue: T;\n streams?: PromptStreams;\n}): Promise<T | Cancelled> {\n const { select, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<T | Cancelled>(streams, null, async (signal) => {\n // Instantiated at `string`, not at `T`: clack's `Option<Value>` is a conditional\n // type that a generic `T extends string` cannot resolve. The values come from\n // this call's own choices, so narrowing the answer back is sound.\n const answer = await select<string>({\n message: opts.message,\n options: opts.choices.map((c) => ({\n value: c.value as string,\n label: c.label,\n ...(c.hint !== undefined ? { hint: c.hint } : {}),\n })),\n initialValue: opts.initialValue,\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : (answer as T);\n });\n}\n\n/** A yes/no confirm. Cancelling, or an input that ends, reads as no. */\nexport async function confirmChoice(\n message: string,\n initialValue = true,\n streams: PromptStreams = {},\n): Promise<boolean> {\n const { confirm, isCancel } = await import('@clack/prompts');\n const resolved = resolveStreams(streams);\n return withInputEnd<boolean>(resolved, false, async (signal) => {\n const answer = await confirm({\n message,\n initialValue,\n input: resolved.input,\n output: resolved.output,\n signal,\n });\n return isCancel(answer) ? false : answer;\n });\n}\n\n/** Open the walkthrough's prompt sequence with a title bar. */\nexport async function intro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.intro(message, { output: process.stderr });\n}\n\n/** Close it, so the last prompt is not left dangling above plain stdout lines. */\nexport async function outro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.outro(message, { output: process.stderr });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY,QAAAC,aAAY;AAC1C,SAAS,eAAe;AAExB,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACPvB,SAAS,OAAO,UAAU,gBAAgB;AAC1C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AACnC,YAAM,IAAI;AAAA,QACR;AAAA,QACA,mBAAmB,IAAI;AAAA,QACvB;AAAA,UACE,KAAK;AAAA,QACP;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["readFile","join","scripts","plans","join","readFile"]}
@@ -1,22 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- runOutcome
4
- } from "./chunk-3NZCU6SD.js";
5
- import "./chunk-BRAVLUGI.js";
6
- import "./chunk-NKN4YC5C.js";
7
- import "./chunk-SPUORKD7.js";
8
- import "./chunk-XGZ5EVMB.js";
9
- import "./chunk-CA3JV7FX.js";
10
- import "./chunk-B676GPS2.js";
11
- import "./chunk-IGHSLJUF.js";
12
- import "./chunk-FKSAUOJU.js";
13
- import "./chunk-736DW4V3.js";
14
- import "./chunk-ELVDOTU7.js";
15
- import "./chunk-ZQIQ55KK.js";
16
- import "./chunk-OC3EIDCP.js";
17
- import "./chunk-PAOVPSP6.js";
18
- import "./chunk-ZXTAQYNA.js";
19
- export {
20
- runOutcome
21
- };
22
- //# sourceMappingURL=outcome-IUSYFJTN.js.map
@@ -1,23 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- runSearch
4
- } from "./chunk-TXVC46SA.js";
5
- import "./chunk-IFPKA32J.js";
6
- import "./chunk-BRAVLUGI.js";
7
- import "./chunk-NKN4YC5C.js";
8
- import "./chunk-SPUORKD7.js";
9
- import "./chunk-XGZ5EVMB.js";
10
- import "./chunk-CA3JV7FX.js";
11
- import "./chunk-B676GPS2.js";
12
- import "./chunk-IGHSLJUF.js";
13
- import "./chunk-FKSAUOJU.js";
14
- import "./chunk-736DW4V3.js";
15
- import "./chunk-ELVDOTU7.js";
16
- import "./chunk-ZQIQ55KK.js";
17
- import "./chunk-OC3EIDCP.js";
18
- import "./chunk-PAOVPSP6.js";
19
- import "./chunk-ZXTAQYNA.js";
20
- export {
21
- runSearch
22
- };
23
- //# sourceMappingURL=search-JVOHEF3E.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/skill-heal.ts"],"sourcesContent":["import { existsSync, lstatSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { emitWriteNotice } from './output';\nimport type { Io } from './output';\nimport { installSkill } from './skill-writer';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { resolveSkillsSource } from './skills-source';\n\nexport interface HealDeps {\n io: Io;\n /** Environment for the CI and opt-out checks. Defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Home whose skills directories are healed. Tests inject a temp dir. */\n homeDir?: string;\n /**\n * The packaged skills source. Defaults to this build's own, and only that\n * default is checked for being a working tree: passing one is a deliberate act.\n */\n skillsSourceDir?: string;\n}\n\n/** The opt-out, in the shape the CLI's other `TENJIN_NO_*` switches take. */\nconst OPT_OUT = 'TENJIN_NO_SKILL_HEAL';\n\n/**\n * Refresh the CLI adapter skills ALREADY in a harness skills directory, so\n * updating the CLI updates the copies `install` wrote instead of leaving an agent\n * on an older version's instructions. Subordinate to the command that ran, like\n * the update nudge: after the envelope, never on stdout, never a failure.\n *\n * It is an UNATTENDED writer into the operator's home, so it is strictly more\n * conservative than `install`, which a human ran on purpose. What it declines to\n * touch is listed on {@link healable}, and it heals only the two CLI adapters:\n * the hosted `tenjin` skill mirrors tenjin.blog/skills.md, so the copy on disk\n * may be a NEWER fetch than this package ships, and rewriting it would undo that\n * and make install's \"re-fetch it from tenjin.blog/skills.md\" false. Same domain\n * `doctor`'s staleness check compares.\n *\n * Unlocked, on purpose. Concurrent healers write byte-identical content to the\n * same paths through per-file atomic renames, so there is nothing to serialize;\n * a lock here could only make things worse, because one left behind by a killed\n * process would silently disable healing on this machine forever.\n */\nexport async function healWiredSkills(deps: HealDeps): Promise<void> {\n try {\n const env = deps.env ?? process.env;\n // The same two doors the update nudge uses: a build log cannot act on this,\n // and an operator who wants their skills left alone says so once.\n if (env.CI !== undefined && env.CI.length > 0) return;\n if (env[OPT_OUT] === '1') return;\n\n const home = deps.homeDir ?? homedir();\n // An empty or relative HOME (sudo/docker env_reset, systemd units) would make\n // every target below relative, healing paths under the working directory.\n if (!isAbsolute(home)) return;\n\n const source = deps.skillsSourceDir ?? packagedSource();\n if (source === null) return;\n const targets = healable(home);\n if (targets.length === 0) return;\n await heal(targets, source, deps.io);\n } catch {\n // Whatever it was, it is the next command's to retry; this one is finished.\n }\n}\n\n/**\n * This build's packaged skills, or null when they are a working tree's. The\n * published package ships `dist/` and `skills/` with no `src/` beside them, so a\n * `src/` sibling means a checkout, whose skills may be half-edited and are not\n * what anyone agreed to install.\n */\nfunction packagedSource(): string | null {\n const dir = resolveSkillsSource(fileURLToPath(new URL('.', import.meta.url)));\n return existsSync(join(dirname(dir), 'src')) ? null : dir;\n}\n\ninterface Target {\n dir: string;\n name: string;\n /** The SKILL.md itself: what the gates judged, and what the notice names. */\n path: string;\n}\n\n/**\n * The (directory, skill) pairs this may rewrite, which is a deliberately narrow\n * set. A skill that is not there is never created, because presence is the\n * operator's consent to a directory.\n *\n * Nothing here is reached THROUGH a symlink. `install` follows one on purpose,\n * since the operator pointed it somewhere; unattended, following one means a\n * write landing wherever it points and a notice naming a path that is not where\n * it landed. That argument does not get weaker one directory up, so every\n * component this CLI creates is checked with `lstat`, not `stat`: the skills\n * directory, the skill directory, and SKILL.md. Above them is the harness's own\n * home, which every tool including the harness reaches through, so a link there\n * is the operator's name for the place rather than a redirect around us.\n *\n * Gating SKILL.md gates the whole write, because it is the only file these skills\n * ship. The other gate, that the file is ours at all, needs its content and so\n * lives at the write itself.\n */\nfunction healable(home: string): Target[] {\n const found: Target[] = [];\n for (const dir of skillsDirsFor(home)) {\n if (!isRealDirectory(dir)) continue;\n for (const name of CLI_SKILL_NAMES) {\n if (!isRealDirectory(join(dir, name))) continue;\n const path = join(dir, name, 'SKILL.md');\n if (lstatSync(path, { throwIfNoEntry: false })?.isFile() !== true) continue;\n found.push({ dir, name, path });\n }\n }\n return found;\n}\n\n/** A directory, and not a symlink to one. */\nfunction isRealDirectory(path: string): boolean {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n}\n\nasync function heal(targets: readonly Target[], source: string, io: Io): Promise<void> {\n const updated: string[] = [];\n for (const { dir, name, path } of targets) {\n try {\n if (!(await isOurs(path, name))) continue;\n const { status } = await installSkill(join(source, name), join(dir, name), false, name, {\n followSymlinks: false,\n });\n if (status === 'up-to-date') continue;\n updated.push(path);\n } catch {\n // A denied write, a case collision, a file swapped under us: that skill keeps\n // what it has and the others are still healed, and NOTHING is said about it.\n // A cause the next command cannot clear either (a directory at 0500) would\n // otherwise print the same line forever, on every command, with no state to\n // suppress it and no way to dismiss it. `tenjin doctor` is where a skill that\n // is wired but not from this build gets reported, which is exactly this.\n }\n }\n if (updated.length > 0) emitWriteNotice(io, noticeFor(updated));\n}\n\n/** Does this file claim to BE the skill we would write over it? Somebody else's\n * skill is not ours to replace just for sitting at one of our paths. */\nasync function isOurs(path: string, name: string): Promise<boolean> {\n const read = await readSkillFile(path);\n return read.kind === 'ok' && skillFrontmatterName(read.bytes.toString('utf8')) === name;\n}\n\n/**\n * Files, not directories: this line is the only notice that content in the\n * operator's home changed unasked, so it has to say which content. It claims\n * nothing about edits being lost, because it cannot know. Every routine upgrade\n * rewrites these same files, and telling someone their edits are gone when they\n * made none is worse than saying nothing.\n */\nfunction noticeFor(updated: readonly string[]): string {\n return `Updated ${updated.join(' and ')} to match this CLI.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,iBAAiB;AACtC,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY,YAAY;AAC1C,SAAS,qBAAqB;AA0B9B,IAAM,UAAU;AAqBhB,eAAsB,gBAAgB,MAA+B;AACnE,MA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,UAAI,CAAE,MAAM,OAAO,MAAM,IAAI,EAAI;AACjC,YAAM,EAAE,OAAO,IAAI,MAAM,aAAa,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,IAAI,GAAG,OAAO,MAAM;AAAA,QACtF,gBAAgB;AAAA,MAClB,CAAC;AACD,UAAI,WAAW,aAAc;AAC7B,cAAQ,KAAK,IAAI;AAAA,IACnB,QAAQ;AAAA,IAOR;AAAA,EACF;AACA,MAAI,QAAQ,SAAS,EAAG,iBAAgB,IAAI,UAAU,OAAO,CAAC;AAChE;AAIA,eAAe,OAAO,MAAc,MAAgC;AAClE,QAAM,OAAO,MAAM,cAAc,IAAI;AACrC,SAAO,KAAK,SAAS,QAAQ,qBAAqB,KAAK,MAAM,SAAS,MAAM,CAAC,MAAM;AACrF;AASA,SAAS,UAAU,SAAoC;AACrD,SAAO,WAAW,QAAQ,KAAK,OAAO,CAAC;AACzC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/uninstall.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport {\n KEPT_ITEMS,\n removeFromSettings,\n removeHookScripts,\n removeMarkerLines,\n removeSkills,\n type UninstallReport,\n} from '../lib/uninstall';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin uninstall`: undo exactly what `tenjin install` wrote, and nothing else.\n *\n * The shape of this command is the promise it makes. It removes the skills, the\n * hook scripts, our hook entries and permission rules in the harness's\n * settings.json, and the legacy pointer line older versions wrote into\n * CLAUDE.md/AGENTS.md. It does NOT remove the wallet, the config, the library,\n * the search ledger, or parked candidates — `install` did not create those, and\n * a wallet holds funds while a candidate is unpublished work. The receipt names\n * what was kept on every run, so the operator learns the boundary from the\n * command rather than from the docs.\n *\n * IDEMPOTENT BY CONSTRUCTION. Every step is \"remove it if it is ours and there\",\n * so a half-installed machine, an already-uninstalled one, and a machine that\n * never ran install all succeed and report what was (not) found. There is no\n * confirmation prompt and no --force: nothing here is unrecoverable, since a\n * `tenjin install` puts all of it back.\n */\n\nexport interface UninstallDeps {\n /** Home whose harness directories are cleaned; tests inject a temp dir. */\n home?: string;\n}\n\nexport async function runUninstall(\n ctx: CommandContext,\n deps: UninstallDeps = {},\n): Promise<CommandResult> {\n const home = deps.home ?? homedir();\n\n // Settings first: it is the only step with a concurrency guard, and the only\n // one that can refuse. Doing it before the scripts are deleted means a refusal\n // leaves a registered hook still pointing at a script that exists, rather than\n // at one that does not.\n const settings = await removeFromSettings(home);\n const scripts = await removeHookScripts(ctx.dataDir);\n const skills = await removeSkills(home);\n const markers = await removeMarkerLines(home);\n\n const report: UninstallReport = {\n settings,\n skills,\n scripts: scripts.scripts,\n ...(scripts.removedDir !== undefined ? { hooksDir: scripts.removedDir } : {}),\n markers,\n kept: [...KEPT_ITEMS],\n };\n\n return { data: report, humanLines: humanLines(report) };\n}\n\nfunction humanLines(report: UninstallReport): string[] {\n const { settings } = report;\n const removed: string[] = [];\n for (const dir of report.skills) removed.push(`skill ${sanitizeForTerminal(dir)}`);\n for (const script of report.scripts) removed.push(`hook script ${sanitizeForTerminal(script)}`);\n if (report.hooksDir !== undefined) {\n removed.push(`empty hooks directory ${sanitizeForTerminal(report.hooksDir)}`);\n }\n for (const event of settings.hooks) {\n removed.push(`${event} hook entry in ${sanitizeForTerminal(settings.path)}`);\n }\n if (settings.rules.length > 0) {\n removed.push(\n `${settings.rules.length} tenjin permission rule(s) in ${sanitizeForTerminal(settings.path)}`,\n );\n }\n for (const path of report.markers) {\n removed.push(`legacy pointer line in ${sanitizeForTerminal(path)}`);\n }\n\n const lines =\n removed.length === 0\n ? ['Nothing to remove; tenjin was not installed here.']\n : ['Removed:', ...removed.map((r) => ` - ${r}`)];\n\n // Named on EVERY run, including the nothing-to-remove one: the boundary is the\n // point of the command, and an operator reaching for it is usually worried\n // about exactly these five things.\n lines.push('Kept (uninstall never touches these):');\n for (const item of report.kept) lines.push(` - ${item}`);\n\n if (settings.warning !== undefined)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ACF;AACA,aAAW,QAAQ,OAAO,SAAS;AACjC,YAAQ,KAAK,0BAA0B,oBAAoB,IAAI,CAAC,EAAE;AAAA,EACpE;AAEA,QAAM,QACJ,QAAQ,WAAW,IACf,CAAC,mDAAmD,IACpD,CAAC,YAAY,GAAG,QAAQ,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,CAAC;AAKpD,QAAM,KAAK,uCAAuC;AAClD,aAAW,QAAQ,OAAO,KAAM,OAAM,KAAK,OAAO,IAAI,EAAE;AAExD,MAAI,SAAS,YAAY,QAAW;AAClC,UAAM,KAAK,KAAK,oBAAoB,SAAS,OAAO,CAAC,EAAE;AAAA,EACzD;AACA,QAAM,KAAK,mCAAmC;AAC9C,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/update.ts","../src/lib/install-location.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { CliError } from '../lib/errors';\nimport { MANAGERS, classifyManager, refuse, resolveManagerScript } from '../lib/install-location';\nimport type { Delegable } from '../lib/install-location';\nimport { emitWriteNotice, sanitizeForTerminal } from '../lib/output';\nimport { channelTag, fetchDistTags, isNewer, resolveTarget } from '../lib/update-check';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin update`: replace this install with the newest version npm offers it,\n * by spawning the package manager that OWNS the install rather than\n * reimplementing one. Four invariants:\n *\n * - The argv pins the EXACT version the registry just named, never the tag, so\n * the check and the install cannot disagree about what ships, and the version\n * string is certified parseable by the same `isNewer` gate the nudge trusts\n * before it goes anywhere near an argv.\n * - The owner performs the install. npm, pnpm and bun are each driven with their\n * own global-add command, because the PATH race that makes a second install\n * dangerous comes from CROSS-manager writes, not from asking the owner to do\n * what it already owns. What cannot be driven is refused instead of guessed\n * at: a source checkout updates by git, an npx run has nothing installed to\n * replace, a project-local copy updates where it is declared, and yarn's\n * global install exists only in yarn 1. See lib/install-location.\n * - The child is a binary or `node <script>`, never a shell. That is what makes\n * the pinned argv worth pinning, and it is the only form that works on win32.\n * - The manager's chatter goes to stderr (live, human mode only, sanitized) and\n * its failure into the error envelope; stdout stays the one envelope every\n * command emits.\n */\n\n/** How long the npm child gets before it is killed. npm's own retry budget runs\n * into minutes, and an agent's turn should not hang on a wedged registry. */\nconst INSTALL_TIMEOUT_MS = 300_000;\n\nexport interface UpdateOptions {\n /** Report whether a newer version exists; never install. */\n check: boolean;\n}\n\n/**\n * How the child ended. Never rejects: all three outcomes are envelope-shaped\n * facts the caller reports, not exceptions, and each is separately testable.\n */\nexport type SpawnResult =\n { kind: 'exit'; code: number } | { kind: 'start-failed'; cause: unknown } | { kind: 'timeout' };\n\nexport type UpdateSpawn = (\n cmd: string,\n args: string[],\n opts: { cwd: string; timeoutMs: number },\n onOutput: (chunk: string) => void,\n) => Promise<SpawnResult>;\n\n/** What to spawn for one manager: a command and any argv that must precede its own. */\ninterface ResolvedManager {\n cmd: string;\n prefix: readonly string[];\n}\n\n/**\n * Turn a manager into a spawnable command. A resolved script runs under THIS\n * node, keeping `shell` unset on every platform; otherwise the bare binary name\n * is used, which is correct for a native binary and fails closed on win32 for a\n * `.cmd` shim.\n */\nfunction resolveManager(manager: Delegable, deps: UpdateDeps): ResolvedManager {\n const script =\n deps.managerScript !== undefined\n ? deps.managerScript\n : resolveManagerScript(manager, process.execPath);\n return script === null\n ? { cmd: MANAGERS[manager].bin, prefix: [] }\n : { cmd: process.execPath, prefix: [script] };\n}\n\nexport interface UpdateDeps {\n fetchImpl?: typeof fetch;\n spawnImpl?: UpdateSpawn;\n /** Where this build's code lives on disk; tests point it at fixture trees. */\n moduleDir?: string;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** The owning manager's entry script, or null when it has none to find.\n * Injectable so the argv shape is asserted without depending on the runner. */\n managerScript?: string | null;\n}\n\ninterface UpdateData {\n current: string;\n latest: string;\n channel: 'alpha' | 'latest';\n updateAvailable: boolean;\n updated: boolean;\n}\n\nexport async function runUpdate(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps = {},\n): Promise<CommandResult> {\n const current = deps.currentVersion ?? pkg.version;\n const channel = channelTag(current);\n const moduleDir = deps.moduleDir ?? fileURLToPath(new URL('.', import.meta.url));\n\n // Refused, not defaulted to a channel: a build whose version this package\n // cannot parse has no release line to compare against, and guessing one is how\n // a foreign build gets told it is up to date forever.\n if (channel === null) {\n throw new CliError('REFUSED', `tenjin-cli reports an unrecognizable version (${current})`, {\n fix: 'Reinstall a published build: npm i -g tenjin-cli',\n });\n }\n\n // First stage: everything whose fix string does not need a resolved version,\n // so it answers without the network. An offline contributor in a checkout is\n // told they are in a checkout, not told to go debug their registry access.\n refuse(moduleDir, { check: opts.check, spec: null });\n\n const tags = await fetchDistTags({\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (tags === null) {\n throw new CliError('NETWORK_ERROR', 'Could not read tenjin-cli dist-tags from npm', {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n const latest = resolveTarget(current, tags);\n // The registry answered, it just has nothing on the tags this build follows.\n // Not a NETWORK_ERROR: nothing about the connection is wrong, and telling the\n // user to check their access sends them after a fault that is not there.\n if (latest === null) {\n throw new CliError(\n 'RESOURCE_NOT_FOUND',\n `npm has no published tenjin-cli on the ${channel} or latest tag`,\n { fix: 'Pick a version yourself: npm view tenjin-cli versions' },\n );\n }\n\n const updateAvailable = isNewer(latest, current);\n const data = (updated: boolean): UpdateData => ({\n current,\n latest,\n channel,\n updateAvailable,\n updated,\n });\n\n if (!updateAvailable) {\n return {\n data: data(false),\n // Not \"(alpha channel)\": the answer is no longer bounded by one tag, and\n // naming one was how this line read as authoritative while being wrong.\n humanLines: [`tenjin-cli ${current} is up to date`],\n };\n }\n if (opts.check) {\n return {\n data: data(false),\n humanLines: [\n `tenjin-cli ${latest} is available (you have ${current}).`,\n 'Run tenjin update to install it.',\n ],\n };\n }\n\n // `latest` is argv-safe here: isNewer returned true, so it matched VERSION_RE.\n const spec = `tenjin-cli@${latest}`;\n\n // Second stage: the entries whose fix strings name the version just resolved.\n // Reached only on the install path, since --check has already returned.\n refuse(moduleDir, { check: false, spec });\n\n // Live chatter is a human courtesy only; the tail rides in the error envelope\n // so a piped failure is still diagnosable. Sanitized per line, because npm\n // relays publisher-controlled text (deprecation notices) and a line break is\n // the one control character this stream must keep.\n const human = ctx.io.isTTY && !ctx.flags.json;\n let tail = '';\n const onOutput = (chunk: string): void => {\n tail = (tail + chunk).slice(-2000);\n if (human) ctx.io.stderr.write(chunk.split('\\n').map(sanitizeForTerminal).join('\\n'));\n };\n\n // Whoever owns the install performs it. The PATH-race objection that used to\n // make this a refusal only applies to CROSS-manager writes; invoking the owner\n // is exactly what the refusal used to tell the user to type by hand.\n //\n // The cast is sound only because `refuse` ran directly above and yarn is one\n // of its entries, so the one non-delegable manager has already thrown. Move\n // this line above that call and it becomes a lie.\n const manager = classifyManager(moduleDir) as Delegable;\n const plan = MANAGERS[manager];\n // --ignore-scripts where the manager has it (tenjin-cli has no runtime\n // dependencies and no registry install runs its own `prepare`), and cwd is the\n // home directory so the child never reads a project's config by accident.\n const args = plan.args(spec);\n const resolved = resolveManager(manager, deps);\n const manual = `Run it yourself: ${plan.manual(spec)}`;\n\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n resolved.cmd,\n [...resolved.prefix, ...args],\n { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },\n onOutput,\n );\n if (outcome.kind === 'start-failed') {\n throw new CliError('UPDATE_FAILED', `Could not start ${manager}`, {\n fix: manual,\n cause: outcome.cause,\n });\n }\n if (outcome.kind === 'timeout') {\n throw new CliError(\n 'UPDATE_FAILED',\n `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1000}s`,\n { fix: manual, details: { output: tail } },\n );\n }\n if (outcome.code !== 0) {\n throw new CliError('UPDATE_FAILED', `${manager} ${args.join(' ')} exited ${outcome.code}`, {\n // EACCES on a root-owned global prefix is the common cause; the operator\n // fixing that themselves beats this CLI ever escalating.\n fix: manual,\n details: { output: tail },\n });\n }\n\n emitWriteNotice(\n ctx.io,\n `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`,\n );\n return {\n data: data(true),\n humanLines: [`Updated tenjin-cli ${current} -> ${latest}. New builds pick it up immediately.`],\n };\n}\n\n/**\n * Default spawn: merged stdout+stderr chunks out, an outcome back, no shell.\n * Bounded by its own timer rather than Node's `timeout` option so that a kill\n * this code ordered is distinguishable from any other death by signal.\n */\nexport const spawnCapture: UpdateSpawn = (cmd, args, opts, onOutput) =>\n new Promise((res) => {\n let child;\n try {\n child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], cwd: opts.cwd });\n } catch (cause) {\n // An argv or option Node rejects outright throws here; ENOENT arrives on\n // the 'error' event instead. Both mean the same thing to the caller.\n res({ kind: 'start-failed', cause });\n return;\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill('SIGKILL');\n }, opts.timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.on('error', (cause) => {\n clearTimeout(timer);\n res({ kind: 'start-failed', cause });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n res(timedOut ? { kind: 'timeout' } : { kind: 'exit', code: code ?? 1 });\n });\n });\n","import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { delimiter, dirname, join, sep } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHERE this build is installed, and what that implies about replacing it.\n *\n * Its own module because it answers a different question from the command that\n * uses it: \"what IS this install\" rather than \"how do I replace it\". The\n * refusal set is the load-bearing part, and it got re-cut in three consecutive\n * reviews while it was expressed positionally inside the command body.\n */\n\n/** Managers a global install can be handed back to. yarn is deliberately absent\n * from the delegable set: see the yarn entry in REFUSALS. */\nexport type Delegable = 'npm' | 'pnpm' | 'bun';\n\n/**\n * One reason `npm install -g` would not actually replace THIS build.\n *\n * Each entry carries the three properties that decide WHEN it is evaluated,\n * because expressing them by where the line sat is what made this set get\n * re-cut three times: a missing entry, then a copy on the wrong side of the\n * fetch, then a duplicate that could not run. Declaring them means adding a\n * refusal is a matter of answering three questions, not of guessing a position.\n */\ninterface Refusal {\n /** Does this install location refuse? Pure filesystem, never the network. */\n test: (moduleDir: string) => boolean;\n error: (spec: string, moduleDir: string) => CliError;\n /**\n * Does the fix string name the version the registry just resolved? This is\n * also what decides whether the entry may run BEFORE the fetch: one that does\n * not need a version is evaluated first, so an offline user in a checkout is\n * told they are in a checkout rather than told to go debug their network.\n */\n needsVersion: boolean;\n /**\n * Does it apply to `--check`? Everything here is a reason not to WRITE, and\n * `--check` only reports, so today nothing does. An entry that ever answers\n * yes is one whose test says the REPORT would be wrong, not the install.\n */\n appliesToCheck: boolean;\n}\n\n/**\n * Ordered most-specific first: a checkout and an npx cache are recognizable\n * before any question of which manager or which tree, and the manager entry\n * precedes the global/local one because a pnpm or bun store has its own layout\n * that `isGlobalTree` is not written for.\n */\nexport const REFUSALS: readonly Refusal[] = [\n {\n test: isSourceCheckout,\n error: () =>\n new CliError('REFUSED', 'tenjin-cli is running from a source checkout, not an install', {\n fix: 'Update the checkout instead: git pull && pnpm install',\n }),\n needsVersion: false,\n appliesToCheck: false,\n },\n {\n test: (moduleDir) => moduleDir.split(sep).includes('_npx'),\n error: (spec) =>\n new CliError('REFUSED', 'tenjin-cli is running from the npx cache, not an install', {\n // Writing a global here would \"succeed\" and change nothing: the next\n // `npx tenjin` still resolves its own cached copy.\n fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`,\n }),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // The ONLY manager still refused. `yarn global add` is yarn-1 only, and\n // berry dropped global installs altogether, so there is no one command this\n // can drive across the versions a user might have. Every other manager is\n // delegated to rather than refused (see MANAGERS).\n test: (moduleDir) => classifyManager(moduleDir) === 'yarn',\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli was installed with yarn, whose global install exists only in yarn 1',\n { fix: `yarn global add ${spec}` },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // Scoped to npm on purpose: the prefix-vs-project-root test is written for\n // npm's layout. pnpm's global store and bun's global dir both keep a\n // package.json beside `node_modules`, so an unscoped test would read either\n // as a project-local install and refuse the very case we now delegate.\n test: (moduleDir) => classifyManager(moduleDir) === 'npm' && !isGlobalTree(moduleDir),\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli is a project-local dependency, not a global install',\n {\n fix: `Update it where it is declared: npm i ${spec}`,\n },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n];\n\n/**\n * Evaluate the refusal set, once per stage. `spec` is null before the registry\n * has been asked and the resolved `tenjin-cli@<version>` after, which is what\n * selects the eligible entries: every entry runs in exactly one stage, so no\n * refusal can be reached twice or, as in round three, be written twice and\n * reached once.\n */\nexport function refuse(moduleDir: string, opts: { check: boolean; spec: string | null }): void {\n for (const entry of REFUSALS) {\n if (opts.check && !entry.appliesToCheck) continue;\n if (entry.needsVersion !== (opts.spec !== null)) continue;\n if (entry.test(moduleDir)) throw entry.error(opts.spec ?? '', moduleDir);\n }\n}\n\n/**\n * The published package ships `dist/`, `docs/`, and `skills/` with no `src/`\n * beside them (the `files` array), so a `src/` next to the nearest package.json\n * means a checkout, whose version number says nothing about what HEAD holds.\n * Same test skill-heal uses to keep its hands off working-tree skills.\n */\nexport function isSourceCheckout(moduleDir: string): boolean {\n let dir = moduleDir;\n for (let i = 0; i < 8; i += 1) {\n if (existsSync(join(dir, 'package.json'))) return existsSync(join(dir, 'src'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\n/**\n * Is this a GLOBAL npm tree? A global install sits under a prefix directory that\n * is not itself a package (`<prefix>/lib/node_modules/tenjin-cli` on POSIX,\n * `<prefix>\\node_modules\\tenjin-cli` on win32), while a project-local one sits\n * under the project root, which by definition has a package.json. That parent is\n * the whole test, which is why it holds for homebrew, nvm, volta and a\n * user-set `npm config prefix` alike without this code enumerating any of them.\n */\nexport function isGlobalTree(moduleDir: string): boolean {\n const segs = moduleDir.split(sep);\n const i = segs.lastIndexOf('node_modules');\n if (i <= 0) return false;\n return !existsSync(join(segs.slice(0, i).join(sep), 'package.json'));\n}\n\n/**\n * Which package manager owns this install, read off the on-disk path. Node\n * resolved the bin symlink before loading us, so the segments name the real\n * store: pnpm's virtual store keeps a literal `.pnpm` segment (or\n * `pnpm/global` for older layouts), bun installs under `.bun`, yarn under\n * `.yarn` or `yarn/global`. Everything else is treated as npm's tree; that\n * covers nvm and volta, both of which route `npm i -g` correctly.\n */\nexport function classifyManager(moduleDir: string): Delegable | 'yarn' {\n const segs = moduleDir.split(sep);\n const pair = (a: string, b: string): boolean => segs.includes(a) && segs.includes(b);\n if (segs.includes('.pnpm') || pair('pnpm', 'global')) return 'pnpm';\n if (segs.includes('.bun')) return 'bun';\n if (segs.includes('.yarn') || pair('yarn', 'global')) return 'yarn';\n return 'npm';\n}\n\n/**\n * How to perform a global install with each manager we delegate to.\n *\n * `scriptSuffixes` is what a PATH shim may resolve to that Node can run\n * directly, which is how win32 is served without a shell: npm and pnpm ship as\n * JS, so the child becomes `node <script>`. An empty list means the binary is\n * native (bun), where spawning it by name already works on every platform.\n */\nexport const MANAGERS: Record<\n Delegable,\n {\n bin: string;\n scriptSuffixes: readonly string[];\n /** Ships beside the running node, as npm does inside the Node distribution. */\n besideNode: boolean;\n args: (spec: string) => string[];\n manual: (spec: string) => string;\n }\n> = {\n npm: {\n bin: 'npm',\n scriptSuffixes: ['npm-cli.js'],\n besideNode: true,\n args: (spec) => ['install', '-g', '--ignore-scripts', spec],\n manual: (spec) => `npm i -g ${spec}`,\n },\n pnpm: {\n bin: 'pnpm',\n // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.\n scriptSuffixes: ['.cjs', '.js'],\n besideNode: false,\n args: (spec) => ['add', '-g', '--ignore-scripts', spec],\n manual: (spec) => `pnpm add -g ${spec}`,\n },\n bun: {\n bin: 'bun',\n scriptSuffixes: [],\n besideNode: false,\n // No --ignore-scripts: bun's flag surface for it is not stable across the\n // versions in the wild, and an unknown flag would fail the install outright.\n args: (spec) => ['add', '-g', spec],\n manual: (spec) => `bun add -g ${spec}`,\n },\n};\n\n/**\n * npm's own entry script, so the child can be `node npm-cli.js` rather than the\n * `npm` shim.\n *\n * On win32 the shim is `npm.cmd`, which Node refuses to spawn without\n * `shell: true`, and `shell: true` is exactly what this command must not do —\n * it would hand back the argv safety the pinned version buys.\n *\n * Deliberately NOT \"npm ships inside the Node distribution\". That is a property\n * of the installer, not of Node: Homebrew's plain `node` formula keeps only\n * corepack in the keg and puts npm at the brew prefix, so a probe relative to\n * `process.execPath` alone returns null on one of the most common macOS setups.\n * So the layout is searched, not assumed — beside the running binary first\n * (official tarball and installer, nvm, volta, versioned brew kegs), then off\n * PATH, where on POSIX the `npm` shim is itself a symlink to `npm-cli.js` and on\n * win32 `npm.cmd` has `node_modules` beside it. Still null when npm cannot be\n * found at all; the caller then falls back to the bare shim, which works\n * everywhere but win32 and fails closed there into UPDATE_FAILED carrying the\n * manual command.\n */\nexport function resolveNpmCli(\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return resolveManagerScript('npm', execPath, env);\n}\n\n/**\n * The JS entry script for `manager`, or null when it has none to find (a native\n * binary, or a shim this cannot see through). Null means \"spawn the bare name\",\n * which works everywhere but win32 and fails closed there.\n */\nexport function resolveManagerScript(\n manager: Delegable,\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const plan = MANAGERS[manager];\n if (plan.scriptSuffixes.length === 0) return null;\n const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;\n return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);\n}\n\n/** A manager's script relative to a directory holding `node` or its own shim. */\nfunction scriptNear(dir: string, bin: string): string | null {\n const candidates = [\n join(dir, 'node_modules', bin, 'bin', `${bin}-cli.js`),\n join(dir, '..', 'lib', 'node_modules', bin, 'bin', `${bin}-cli.js`),\n ];\n return candidates.find(isFile) ?? null;\n}\n\n/**\n * Walk PATH for the manager's shim and turn it into its script. Probes the\n * PATHEXT extensions on win32 for the same reason `onPath` in skill-wiring.ts\n * does: the real file there is `npm.cmd`, never a bare `npm`.\n */\nfunction scriptOnPath(\n bin: string,\n suffixes: readonly string[],\n env: NodeJS.ProcessEnv,\n): string | null {\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 (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (!isFile(join(part, `${bin}${ext}`))) continue;\n // POSIX package managers link the shim straight at the script, which is\n // what makes this layout-independent rather than a longer guess list.\n //\n // The endsWith is a CORRECTNESS check, not a security guard: it asks \"did\n // this symlink land on npm's script or on something else\", and a shim\n // pointed elsewhere returns null, which falls back to spawning that same\n // retargeted shim anyway. PATH poisoning is out of scope by construction —\n // an attacker ahead of npm on PATH owns every tool the user runs, and the\n // pre-existing fallback `spawn('npm', ...)` resolved through the same PATH.\n const real = realpathOrNull(join(part, `${bin}${ext}`));\n if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;\n const near = scriptNear(part, bin);\n if (near !== null) return near;\n }\n }\n return null;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nfunction realpathOrNull(p: string): string | null {\n try {\n return realpathSync(p);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACF9B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,WAAW,SAAS,MAAM,WAAW;AAkDvC,IAAM,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