diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index aaf2973..44dae82 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: fetch-depth: 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f19dea2..3d14ce4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,16 +19,16 @@ jobs: matrix: os: [ubuntu-latest, macos-latest, windows-latest] steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: ref: ${{ inputs.sha || github.sha }} - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + - uses: actions/setup-java@v6 with: distribution: temurin java-version: 25 - - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + - uses: gradle/actions/setup-gradle@v6 - name: Build and test run: ./gradlew build @@ -65,16 +65,16 @@ jobs: generated-project-build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: ref: ${{ inputs.sha || github.sha }} - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + - uses: actions/setup-java@v6 with: distribution: temurin java-version: 25 - - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + - uses: gradle/actions/setup-gradle@v6 - name: Generate project run: | diff --git a/.github/workflows/jmix-release-check.yml b/.github/workflows/jmix-release-check.yml index 1985109..845b40f 100644 --- a/.github/workflows/jmix-release-check.yml +++ b/.github/workflows/jmix-release-check.yml @@ -17,7 +17,7 @@ jobs: env: JMIX_VERSION: ${{ inputs.jmix_version }} steps: - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + - uses: actions/setup-java@v6 with: distribution: temurin java-version: 25 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1fb893e..c15384e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,7 +28,7 @@ jobs: sha: ${{ steps.release.outputs.sha }} version: ${{ steps.release.outputs.version }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: ref: ${{ github.sha }} @@ -101,16 +101,16 @@ jobs: artifact: windows-x64 steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: ref: ${{ needs.prepare.outputs.sha }} - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + - uses: actions/setup-java@v6 with: distribution: temurin java-version: 25 - - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + - uses: gradle/actions/setup-gradle@v6 - name: Build and package shell: bash @@ -126,7 +126,7 @@ jobs: shell: pwsh run: tests/test-install.ps1 - - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + - uses: actions/upload-artifact@v7 with: name: release-${{ matrix.artifact }} path: build/release/* @@ -141,11 +141,11 @@ jobs: contents: write steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7 with: ref: ${{ needs.prepare.outputs.sha }} - - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + - uses: actions/download-artifact@v8 with: pattern: release-* path: release diff --git a/AGENTS.md b/AGENTS.md index 8a595d6..fe8df7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Read the guide relevant to the change; update it when behavior changes. | [Project generation](docs/features/project-generation.md) | Templates, repository cache, rendering, locales, Git | | [Wizard](docs/features/wizard.md) | Steps, navigation, terminal fallbacks, demo recording | | [Add-ons](docs/features/add-ons.md) | Studio catalog, compatibility, selection, translations, installation | -| [Environment and Agent Toolkit](docs/features/environment-and-toolkit.md) | Development JDKs, project launching, AI agent setup | +| [Environment and Agent Toolkit](docs/features/environment-and-toolkit.md) | Development JDKs, project launching, AI agent setup, `agent-toolkit` | | [Updates](docs/features/updates.md) | Startup checks, self-update, cache cleanup | | [Account and trial](docs/features/account-and-trial.md) | Sign-in, session file, trial download | @@ -58,7 +58,7 @@ Additional checks depend on the change: | Change | Required checks | |----------------------------------------|---------------------------------------------------------------------------------------------------| -| Commands/options | `jmix --help`, `jmix new --help`, and non-interactive use | +| Commands/options | `jmix --help`, `jmix new --help`, `jmix agent-toolkit --help`, and non-interactive use | | Templates, repository access, or generation | `JMIX_CLI_IT=true ./gradlew test` | | Generation | Also generate and build a project as described in the feature guide | | Wizard | Real terminal and numbered/line-input fallback, including back and quit | diff --git a/README.md b/README.md index 0f9dd39..dcab290 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Create [Jmix](https://www.jmix.io/) projects from the same templates as Jmix Stu Use the interactive wizard or run the CLI from a script or an AI agent. -Jmix CLI command menu and wizard: add-on search, Agent Toolkit setup, and project generation +Jmix CLI demo: jmix new creates a project in a guided wizard, and jmix agent-toolkit sets up skills, guidelines, and MCP servers for AI agents ## Install @@ -48,6 +48,32 @@ See [wizard controls](docs/features/wizard.md), [project generation](docs/features/project-generation.md), and [commercial add-on setup](docs/features/add-ons.md#commercial-add-ons). +## Agent Toolkit + +Run `jmix agent-toolkit` to add or update the +[Jmix Agent Toolkit](https://github.com/jmix-framework/jmix-agent-toolkit) in an +existing Jmix project. Choose the project (or pass `--path`), then check the +steps to run, or pass them as arguments: + +- `skills` — install or update the agent skills. +- `guidelines` — add or update the Jmix guidelines in `AGENTS.md`. +- `mcp` — configure MCP servers for the selected AI agents. + +The checklist shows the state of each step and leaves the up-to-date ones +unchecked. From a script, `--non-interactive` runs the named steps, or all +three when none are named, without prompts: + +```shell +cd demo +jmix agent-toolkit --non-interactive +jmix agent-toolkit skills guidelines --non-interactive +``` + +The command lists the files the toolkit reports as changed, and its notes. Run +`jmix agent-toolkit --help` for the options and the MCP servers and AI agents the +toolkit currently offers. See the +[Agent Toolkit guide](docs/features/environment-and-toolkit.md#toolkit-command). + ## Jmix account and trial Sign in to download the Enterprise+BPM trial project. diff --git a/docs/demo.gif b/docs/demo.gif index 484ad65..09deb88 100644 Binary files a/docs/demo.gif and b/docs/demo.gif differ diff --git a/docs/features/account-and-trial.md b/docs/features/account-and-trial.md index b2a092e..ed568aa 100644 --- a/docs/features/account-and-trial.md +++ b/docs/features/account-and-trial.md @@ -197,7 +197,8 @@ and the archive has no `.gitignore`. - The archive stores no Unix permissions, so every `gradlew` is made executable. The folders then move into place and the staging folder goes away. -The report reads `bomVersion` from the root or `demo/*` build files (a `.trial` suffix is +The report reads `bomVersion` from the root or `demo/*` build files, else the `io.jmix` +plugin version from the same files (a `.trial` suffix is dropped; only the shape is checked, because trials run on the newest Jmix) and runs the same JDK check as `jmix new`, which reports and never fails the command. Then it prints the location, the end date, a general module run command with one real example and its URL, diff --git a/docs/features/environment-and-toolkit.md b/docs/features/environment-and-toolkit.md index ba38fb6..a34b266 100644 --- a/docs/features/environment-and-toolkit.md +++ b/docs/features/environment-and-toolkit.md @@ -23,27 +23,200 @@ version. Do not report the private bundled runtime as an installed development J its own port. Non-interactive trial downloads do not open or run projects. - Install Jmix Agent Toolkit from the branch matching the Jmix major version unless the user opts out (`--no-agents-toolkit` or the wizard's setup checklist). - Shared guidelines go into `AGENTS.md`, and project-local skills are real folders - in `.agents/skills`, read by Codex, OpenCode, Junie and other agents. Claude Code - is enabled by default: `.claude/skills` links each skill to the shared store, - and a new `CLAUDE.md` imports `@AGENTS.md`. -- Run the Toolkit's project-scoped MCP setup for Codex - (`.codex/config.toml`), Claude Code (`.mcp.json`), OpenCode - (`opencode.json`), and Junie (`.junie/mcp/mcp.json`). The Toolkit merges - Jmix Docs and Playwright into each config and selects the JetBrains - transport for Codex, Claude Code, and OpenCode. Junie has native IDE access. - Jmix Docs requires no API key. On macOS and Linux, merging JSON requires - `jq` or Node.js. Enable the MCP server in IntelliJ IDEA and make `npx` - available for Playwright and Junie's Jmix Docs bridge. Trust the project - in Codex and approve the project servers in Claude Code. - The CLI isolates Claude Desktop's user profile from the MCP setup step. - Set up Context7 separately with your API key in the agent's user settings. + `jmix new` runs the skills, guidelines, and MCP steps with every MCP server + and AI agent the toolkit offers, as `jmix agent-toolkit --non-interactive` does. A missing + `v` branch fails the setup; there is no fallback to the default branch. +- Single source of truth: keep no copy of the toolkit's reference data in code, + help texts, or guides. That covers server and agent ids, labels and defaults, + per-agent config files, skill names, the skills folder, and the guidelines + text. Read it at run time from the project's toolkit branch: + - MCP servers and AI agents: `.studio/studio-meta-data.json`, step `mcp`, + inputs `mcpServers` and `mcpAgents`; each agent's project MCP config file + is its `projectConfig`, and the servers it never gets are its `skipServers`. + - Skill names, the project skills folder, and the content hash: + `.studio/skills-manifest.json` (`skills`, `store.local`, `sha256`). + - The current guidelines block: `content/guidelines-block.md`. + - The paths a run changed: the installer's `@@JMIX_CHANGE@@` lines. + - What to do after a run: the installer's own notes. + + The [toolkit's README](https://github.com/jmix-framework/jmix-agent-toolkit) + describes what it installs; `jmix agent-toolkit --help` lists the current servers + and agents. +- Only the installer's calling contract stays in code: the script names, the + `skills`, `agents-md`, and `mcp` subcommands with their flags, the three file + paths above, and the JSON keys read from them. Apply the same rule to any other + third-party tool the CLI drives. +- Two guards must work without the network and keep their own toolkit knowledge: + the CLI isolates Claude Desktop's user profile from the MCP step, and checks + the project paths of the selected steps before the first one runs. A path the + skills or guidelines step writes must not be a link that leads outside the + project; a dangling symbolic link counts by the target it would create, so + `CLAUDE.md -> AGENTS.md` passes before `AGENTS.md` exists (a dangling Windows + junction is refused). The skills paths include every `./skills` that + holds a `jmix`, `jmix-*` or `jmix.*` entry, which a local skills run tidies. + An MCP config path must not be a link at all (a Windows junction counts); a + name that differs in letter case alone is no link. +- Toolkit files are external input. Check ids and paths before they reach a path + or an argument list, and remove control characters from any toolkit text that + is printed. - JDK and toolkit installation report their phases (lookup, download with byte - counts, checksum, unpacking; installer download, skills, guidelines, MCP) through - `onStatus`/`onProgress` callbacks so the CLI can show a progress indicator. -- Toolkit setup runs its downloaded installer with fixed argument lists. Keep - setup local to the generated project. Report installer failures as warnings - with a retry link. + counts, checksum, unpacking; installer download, metadata, skills, guidelines, + MCP) through `onStatus`/`onProgress` callbacks so the CLI can show a progress + indicator. +- Toolkit setup runs its downloaded installer as a file with a complete argument + list, never through a shell string, so the installer never prompts. Steps run + in the project, so the shell (`bash`, or Windows PowerShell) is started by its + absolute path, and each step gets a PATH without empty or relative entries (a + leading `~` becomes the user's home). Outside Windows a missing or emptied PATH + becomes `/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`: with none, bash would + look in the project. Keep setup + local to the project: never pass the global scope, a flag that turns an agent + off, or a server or agent the toolkit metadata does not offer. `jmix new` + reports installer failures as warnings that name `jmix agent-toolkit`. + +## Toolkit command + +`jmix agent-toolkit` adds or updates the toolkit in an existing project: + +```text +jmix agent-toolkit [skills] [guidelines] [mcp] + [--path DIR] [--jmix-version VERSION] + [--servers CSV] [--agents CSV] [--non-interactive] +``` + +- The steps named as arguments run, each once and in the order of the table + below; the command prints the result and exits. Without steps the interactive + command asks with the steps checklist, and `--non-interactive` runs all three. + An empty choice in the checklist runs nothing and ends with + `Nothing selected, so nothing was changed.` (exit code 0). See the + [wizard guide](wizard.md) for the checklist, Back, and the line-input fallback. +- Project: a directory with `build.gradle`, `build.gradle.kts`, + `settings.gradle`, or `settings.gradle.kts`. `--path` names it; otherwise a + scripted run uses the current directory, and the interactive command first + asks which project to use. The list offers the current directory when it is a + Gradle project, then the Jmix projects one level below it and in + `~/IdeaProjects` (by name, hidden folders aside), then `Other...` for a typed + directory with Tab completion. Started in the home directory, the list does + not look into the home directory's own folders: on macOS that asks for access + to Desktop, Documents, and Downloads. A scripted run, and any run whose explicit + `--path` is not a project, fails + with ``No Gradle project found in . Run `jmix agent-toolkit` from the project root or pass --path.`` +- Jmix version: `--jmix-version`, else the first literal `bomVersion` in the root + or `demo/*` build files, else the first `io.jmix` Gradle plugin version in + the same files. A value that does not look like a version is + skipped; a value without a numeric major counts as not detected. + When none is found the interactive command asks for it; a + scripted run fails with `Cannot detect the Jmix version in . Pass --jmix-version.` + A `--jmix-version` without a numeric major fails before any question with + `Unexpected Jmix version format: `. +- The toolkit branch is `v`. A missing branch fails with + `Agent Toolkit setup failed: the toolkit has no v branch for Jmix yet`. +- Choices: the MCP servers and AI agents come from the metadata of the project's + branch, in the toolkit's order. A choice is offered when the toolkit enables it + by default (`default: true`). A server is not offered when the `mcp` step has a + text input for it: an input of type `userInput` whose id starts with the + server's id, both compared without case and by their letters and digits alone. + Every offered choice is selected by default. +- A choice is ignored unless its id starts with a letter or digit and continues + with letters, digits, `.`, `_`, or `-`. Metadata without the `mcp` step, without + one of the two lists, or with a list that ends up empty is an error: + `Unexpected Agent Toolkit metadata format.` +- `--servers` and `--agents` take offered ids, comma-separated and without case, + and default to all of them. An unknown id fails and names the valid values; an + empty list fails too. Both apply to the `mcp` step only: steps named without + `mcp` make them fail, and in the checklist they keep `mcp` checked. An + interactive run with `mcp` asks for each list that its option does not decide. +- Steps, in this order: + + | Step | Toolkit call | Writes | + |--------------|--------------------------------------------|-------------------------------------------| + | `skills` | `skills --scope local` | The project skills folder and its links | + | `guidelines` | `agents-md` | The Jmix block in `AGENTS.md` | + | `mcp` | `mcp --servers … --agents … --scope local` | The project config of each selected agent | + + The toolkit decides the files of each step, including the ones it adds for + single agents and the backups of files it changes. +- The link guard and the metadata are checked before the first step runs, so a + run never stops halfway for them. Every toolkit failure of a run (download, + metadata, a step) is one line that starts with `Agent Toolkit setup failed:`. + The first failed step stops the run: its line names the step and ends with + the installer's error lines, or with the tail of its output when it printed + none. +- Changes come from markers, not from log text: steps run with + `JMIX_EMIT_CHANGE_MARKERS=1`, and each `@@JMIX_CHANGE@@` line gives an action + and a path. Keep the first action per path, and print paths inside the project + relative to it. The result is a green headline and one row per path with the + toolkit's action word; an action this CLI version does not know is listed + without color. Without changes the headline says `already up to date`. A run + of some of the steps names them and speaks for them alone, as in + `Agent Toolkit v3: guidelines, mcp already up to date`. +- Step output is read as UTF-8 when it is valid UTF-8, else, on Windows, in + the OEM code page: Windows PowerShell 5.1 writes redirected output in the code + page of the new, windowless console Java starts it in, never the user's + console, so a step must inherit no standard stream. UTF-8 goes first so a + console `CodePage` of 65001 in the registry reads right. Limits, all shown + as garbled text and an absolute path, as before this decoding: a character + outside the code page (Cyrillic under code page 437) arrives as `?` or a + look-alike; OEM text that is also valid UTF-8 (rare, such as `сок` under + code page 866) reads as UTF-8; another registry `CodePage` is not followed; + and a code page without a charset in the runtime (720) is read as UTF-8 with + replacement. +- Notes: `Notes from the Agent Toolkit:` lists the installer's own guidance, one + bullet each, whether or not files changed. A terminal breaks a long note at + spaces under its bullet; piped output keeps each note on one line. Select notes by position and by + the `Note:` prefix, never by wording: the lines marked `Note:` in every step, + and in the MCP step also every line that starts at column 0 and is neither a + `[…]` heading nor a marker. The CLI writes no guidance of its own. Notes are + written for the toolkit's installer and can name its flags. +- States: the checklist appends `not installed`, `up to date`, or + `update available` to each step. A step starts checked unless it is up to + date, so a step whose state is unknown starts checked too. When no step + starts checked (every step up to date, and neither `--servers` nor + `--agents` given), the checklist says + `Everything is up to date. Select a step to run it anyway.` The states need + three requests, sent at once with a 3 second limit each; a state is unknown + without its answer. The MCP questions reuse the metadata of this check. Back + to the checklist keeps the earlier choice and does not detect the states + again; choosing the project or the version again does. + - Skills compare the hash of the manifest's skills in its `store.local` + folder with `sha256`. + - Guidelines compare `AGENTS.md` with the published block: it contains the + whole block, else it has a line equal to the block's first line. Bytes + that are not UTF-8 around the block do not matter. + - MCP reads the `projectConfig` file of each offered `mcpAgents` choice. It is + `up to date` when one of them names every offered server its agent gets + (all but the agent's `skipServers`), `not installed` when none of them + exists or names an offered server, and `update available` otherwise. Only + names count: a JSON key (`"id":`) or the last key of a TOML table header + (`[mcp_servers.id]`), read as the installers read it (spaces, quotes, and a + BOM do not count). +- Limits of the states: a checkout with converted line endings (Git `autocrlf`) + hashes differently, so its skills state stays `update available`. MCP + compares names only, so a server with an outdated definition counts as set + up, and a server the user left out keeps MCP at `update available`. One + complete config is enough, as a project may use a single agent, so a config + missing for another agent does not show. Skills and guidelines read only the + skills store and `AGENTS.md`: missing Claude Code links in `.claude/skills` or + a missing `CLAUDE.md` do not count. A `projectConfig` that is not a plain + relative path is ignored, and MCP has no state when no agent has one. + `AGENTS.md` over 4 MiB is not read, nor is an `AGENTS.md` or a skills store + that a link leads out of the project. Links in a skill folder are never + read, so a toolkit file replaced by a link counts as changed. An MCP config that a link + leads out of the project counts as missing; one over 4 MiB, like one that + cannot be read, leaves the state to the others, or makes it unknown. Scripted + runs and runs with step arguments show no states. +- Help: `jmix agent-toolkit --help` ends with the offered server and agent ids, + loaded with a 3 second limit from the branch of the Jmix version detected in + the current directory (`--path` is not used), or from the toolkit's default + branch when none is detected. Without an answer it ends + with `The current MCP servers and AI agents are listed when the Agent Toolkit is reachable.` + Only printed help makes the request, a usage error does not, and option help + texts name no values. +- Expected failures are one line without a stack trace or usage text: raise + them as `CliktError`, not `UsageError`. +- Updating replaces the toolkit's skill folders, so local edits to them are + lost. The command sets up project files only; the toolkit installer and Jmix + Studio cover user-level setup and the choices the command does not offer. ## Code @@ -53,12 +226,23 @@ version. Do not report the private bundled runtime as an installed development J - [JdkInstaller.kt](../../src/main/kotlin/io/jmix/cli/env/JdkInstaller.kt) — managed JDK installation. - [ProjectLauncher.kt](../../src/main/kotlin/io/jmix/cli/env/ProjectLauncher.kt) — IDE, file manager, and Gradle commands. - [ProjectInteraction.kt](../../src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt) — shared follow-up prompts and JDK setup. -- [AgentToolkitInstaller.kt](../../src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt) — toolkit setup. +- [AgentToolkitInstaller.kt](../../src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt) — toolkit steps, change markers, and notes. +- [AgentToolkitMetadata.kt](../../src/main/kotlin/io/jmix/cli/env/AgentToolkitMetadata.kt) — toolkit files and the offered MCP servers and AI agents. +- [AgentToolkitStatus.kt](../../src/main/kotlin/io/jmix/cli/env/AgentToolkitStatus.kt) — the state of each step in a project. +- [ToolkitCommand.kt](../../src/main/kotlin/io/jmix/cli/command/ToolkitCommand.kt) — the `agent-toolkit` command. ## Verification Run `./gradlew test --tests 'io.jmix.cli.env.*'`. Network-backed JDK and toolkit integration tests require `JMIX_CLI_IT=true`. For detection changes, also run a self-contained CLI image so its bundled runtime cannot mask missing JDKs. -For toolkit changes, inspect the generated guidelines, skills, and MCP configs, -including Junie's shared files, and cover Windows command construction. +For toolkit changes, run +`./gradlew test --tests 'io.jmix.cli.env.AgentToolkit*' --tests 'io.jmix.cli.command.ToolkitCommandTest'` +and `JMIX_CLI_IT=true ./gradlew test --tests 'io.jmix.cli.env.AgentToolkitInstallerIntegrationTest'`. +The MCP integration tests read the user's Codex config (`$CODEX_HOME` or +`~/.codex/config.toml`), as the installer does: a global server with the same +name and another transport fails them. +Inspect the generated guidelines, skills, and MCP configs, and cover Windows +command construction. For command changes, also run `jmix agent-toolkit --help`, +a scripted run in a generated project, and the steps checklist in a raw terminal +and a line-input console, including Back and quit. diff --git a/docs/features/wizard.md b/docs/features/wizard.md index 4d0cb70..52819be 100644 --- a/docs/features/wizard.md +++ b/docs/features/wizard.md @@ -4,10 +4,12 @@ Running `jmix` without a command opens the command menu, in this order: 1. `new` — create a new project. 2. `trial` — download the Enterprise+BPM trial project. -3. `login` — sign in, or `logout` — sign out when a local session is saved. -4. `update` — update the CLI. +3. `agent-toolkit` — add or update the AI Agent Toolkit in an existing project. +4. `login` — sign in, or `logout` — sign out when a local session is saved. +5. `update` — update the CLI. -Descriptions come from the commands' help text. The menu checks only the saved +Descriptions come from the commands' help text, short enough that every row, +numbered ones included, fits an 80-column terminal. The menu checks only the saved session; it makes no account request. An expired session can therefore still show `logout` until a command detects the expiry and clears it. Direct command calls and `--help` bypass the menu, and both `login` and `logout` remain available directly. @@ -97,12 +99,47 @@ draft; templates opened during a cancelled run are closed before returning home. location is the parent for the archive's project folder. The run action also asks which demo module to start; Back returns to the checklist. `--path` skips location selection, and non-interactive trial runs skip both interactive steps. +- `jmix agent-toolkit` asks only what its arguments and options leave open, in this + order: the project directory (unless `--path` is given), the Jmix version when + it is not detected, the steps, and with `mcp` the MCP servers and the AI + agents. The project list starts with the current directory when it is a + Gradle project, then lists the Jmix projects one level below it and in + `~/IdeaProjects`, and ends with `Other...`; going back to it keeps the chosen + project selected. Back from a typed directory shows the list again with + `Other...` selected; when `Other...` is the only entry, the list is skipped + and Back leaves the question. The steps checklist lists `skills`, + `guidelines`, and `mcp` with the state of each; the steps that are up to date + start unchecked, and `--servers` or `--agents` keep `mcp` checked. Confirming + it empty runs nothing. The two MCP checklists show the toolkit's labels with + every entry checked. Confirming an empty MCP checklist repeats the question + with the reason. Back to the version question offers the version typed + before. The MCP lists keep their earlier choice after Back, through the steps + checklist too while `mcp` stays checked. +- In `jmix agent-toolkit`, Back (Esc, or `<` in line-input consoles) returns to the + previous question that was asked, and from the first one to the command menu. + This works for both a menu-launched and a direct `jmix agent-toolkit`. `q` quits + from a list. Text questions use Ctrl+Q in raw terminals and have no quit key + in line-input consoles. When the input ends before the questions are + answered, nothing is set up and the command fails with + `No input to answer the questions, so nothing was set up. Use --non-interactive, or pass the answers as arguments and options.` + The project line (the directory alone until its version is known) + and the answers stay above the current question; raw terminals print them + again above the result. A run that asks nothing does not open the alternate + screen. +- Without raw mode the `agent-toolkit` project list is a numbered list, the steps + checklist is a numbered checklist (numbers toggle, Enter confirms), and each MCP + checklist becomes one text question in the syntax of `--servers` and + `--agents`, not one yes/no question per entry. Enter keeps the ids shown (every + offered id, or the earlier answer after Back), an unknown id repeats the + question with the valid values, and `<` goes back. + See the [toolkit command](environment-and-toolkit.md#toolkit-command). ## Code - [JmixCli.kt](../../src/main/kotlin/io/jmix/cli/command/JmixCli.kt) — root command and command menu. - [NewCommand.kt](../../src/main/kotlin/io/jmix/cli/command/NewCommand.kt) — step state and transitions. - [ProjectInteraction.kt](../../src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt) — shared location, next steps, opening, and running. +- [ToolkitCommand.kt](../../src/main/kotlin/io/jmix/cli/command/ToolkitCommand.kt) — `agent-toolkit` questions and Back. - [Prompts.kt](../../src/main/kotlin/io/jmix/cli/wizard/Prompts.kt) — rendering, input, and fallbacks. - [StatusReporter.kt](../../src/main/kotlin/io/jmix/cli/wizard/StatusReporter.kt) — activity indicator for slow steps. - [wizard](../../src/main/kotlin/io/jmix/cli/wizard) — banner, validation, and path completion. @@ -115,16 +152,22 @@ text and search containing `q` and `й`, selection retention, template-included omitted, and narrow/resized terminals. The README GIF is rendered from a film page kept outside the repository. It -recreates a real CLI session in an 80×20 terminal with the CLI's own strings, -colors, clipping, and step order: the command menu, every wizard stage with the -filled answers, add-on search, the setup checklist, the generation progress, -and the printed summary with the reproducible command. The session is -condensed, and the paths are illustrative. Keep pauses long enough to read; -keep search and keyboard hints in place. Show the purple `[$]` badges and the -secondary `[$] - commercial add-on` legend below the picker heading in the catalog. +opens on the install card, then shows two features, each opened by a title card +with the command and one line about it. `jmix new` recreates a real session in an 80×21 terminal with the +CLI's own strings, colors, clipping, and step order: the command menu, the +wizard's name, version, add-on search, and setup checklist (the other answers +stay in the history), the generation progress, and the printed summary with the +reproducible command. `jmix agent-toolkit` recreates the menu, the project +list, the steps checklist with each step's state, the MCP lists, and the +toolkit's report in an existing project. The sessions are condensed, and the +paths are illustrative. Keep pauses long enough to read; keep search and +keyboard hints in place. Show the purple `[$]` badges and the secondary +`[$] - commercial add-on` legend below the picker heading in the catalog. -When the wizard's screens change, capture them again in an 80×20 terminal, -update the film's texts, and render every frame at 800 px wide and 25 fps. +When these screens change, capture them again in an 80×21 terminal (from 21 +rows the command menu keeps its banner), update the film's texts, and render +every frame at 800 px wide and 25 fps. Build the GIF with one FFmpeg palette and Bayer dithering, optimize it with -`gifsicle -O3`, and inspect it at the README's displayed width. The last frames -fade back into the first, so the loop has no seam. +`gifsicle -O3` (lossy compression grains the background glow), and inspect it at +the README's displayed width. At the end the install card builds again, so the +last frames equal the first one and the loop has no seam. diff --git a/src/main/kotlin/io/jmix/cli/Main.kt b/src/main/kotlin/io/jmix/cli/Main.kt index 65fe905..6ca8dfa 100644 --- a/src/main/kotlin/io/jmix/cli/Main.kt +++ b/src/main/kotlin/io/jmix/cli/Main.kt @@ -7,6 +7,7 @@ import io.jmix.cli.command.LoginCommand import io.jmix.cli.command.LogoutCommand import io.jmix.cli.command.NewCommand import io.jmix.cli.command.ReturnToMainMenu +import io.jmix.cli.command.ToolkitCommand import io.jmix.cli.command.TrialCommand import io.jmix.cli.command.UpdateCommand import io.jmix.cli.repo.TemplateRepository @@ -18,14 +19,7 @@ fun main(args: Array) { // Before parsing: an available update is installed and the command re-runs // on the new version, so it never executes on a superseded build. SelfUpdater.runStartupMaintenance(args) - val usageStatistics = UsageStatistics() - val cli = JmixCli().subcommands( - NewCommand(TemplateRepository.defaultCacheDir(), usageStatistics), - TrialCommand(usageStatistics = usageStatistics), - LoginCommand(usageStatistics), - LogoutCommand(), - UpdateCommand(), - ) + val cli = rootCommand(UsageStatistics()) var arguments = args while (true) { try { @@ -36,3 +30,13 @@ fun main(args: Array) { } } } + +/** The root command with its subcommands in the order of the command menu. */ +internal fun rootCommand(usageStatistics: UsageStatistics) = JmixCli().subcommands( + NewCommand(TemplateRepository.defaultCacheDir(), usageStatistics), + TrialCommand(usageStatistics = usageStatistics), + ToolkitCommand(), + LoginCommand(usageStatistics), + LogoutCommand(), + UpdateCommand(), +) diff --git a/src/main/kotlin/io/jmix/cli/WindowsConsole.kt b/src/main/kotlin/io/jmix/cli/WindowsConsole.kt index de2e5de..7d1a27d 100644 --- a/src/main/kotlin/io/jmix/cli/WindowsConsole.kt +++ b/src/main/kotlin/io/jmix/cli/WindowsConsole.kt @@ -2,6 +2,7 @@ package io.jmix.cli import com.sun.jna.Library import com.sun.jna.Native +import java.nio.charset.Charset /** * Switches an attached Windows console to the UTF-8 code page so the wizard's @@ -16,10 +17,33 @@ internal object WindowsConsole { private interface Kernel32 : Library { fun GetConsoleCP(): Int fun GetConsoleOutputCP(): Int + fun GetOEMCP(): Int fun SetConsoleCP(codePage: Int): Boolean fun SetConsoleOutputCP(codePage: Int): Boolean } + /** + * The charset of the OEM code page, the one a new console starts in. Java starts a child whose standard + * streams are all redirected in a console of its own, so Windows PowerShell 5.1 writes redirected output in + * it. Null off Windows, on failure, and for a code page without a charset in the runtime image (720 has none). + */ + val oemCharset: Charset? by lazy { + if (!System.getProperty("os.name", "").startsWith("Windows")) return@lazy null + runCatching { charsetOf(Native.load("kernel32", Kernel32::class.java).GetOEMCP()) }.getOrNull() + } + + /** The charset of a Windows [codePage], named as the JDK names console code pages; null when there is none. */ + fun charsetOf(codePage: Int): Charset? = runCatching { + Charset.forName( + when (codePage) { + UTF8_CODE_PAGE -> "UTF-8" + // cp932 and its kin would be IBM charsets. + in 874..950 -> "ms$codePage" + else -> "cp$codePage" + }, + ) + }.getOrNull() + /** * Enables UTF-8 console code pages; a no-op off Windows, without a console, or on failure. */ diff --git a/src/main/kotlin/io/jmix/cli/command/NewCommand.kt b/src/main/kotlin/io/jmix/cli/command/NewCommand.kt index 34bf177..20013da 100644 --- a/src/main/kotlin/io/jmix/cli/command/NewCommand.kt +++ b/src/main/kotlin/io/jmix/cli/command/NewCommand.kt @@ -953,13 +953,13 @@ class NewCommand internal constructor( private fun installAgentToolkit(info: ProjectCreationInfo, progress: StatusReporter.Handle) { try { progress.relabel("Installing the Jmix Agent Toolkit") - AgentToolkitInstaller.install(info.projectDir, info.jmixVersion, progress::relabel) + AgentToolkitInstaller.install(info.projectDir, info.jmixVersion, onStatus = progress::relabel) progress.println( brightGreen("✓ ") + "Agent Toolkit:" + cyan(" local skills, shared guidelines, and project MCP setup"), ) } catch (e: Exception) { progress.println(brightYellow("Warning: Agent Toolkit installation failed: ${e.message}")) - progress.println(brightYellow("Install it later: https://github.com/jmix-framework/jmix-agent-toolkit")) + progress.println(brightYellow("Install it later: run `jmix agent-toolkit` in the project.")) } } diff --git a/src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt b/src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt index aa1d9bd..f152411 100644 --- a/src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt +++ b/src/main/kotlin/io/jmix/cli/command/ProjectInteraction.kt @@ -17,11 +17,14 @@ import io.jmix.cli.wizard.StatusReporter import io.jmix.cli.wizard.requireValue import java.nio.file.Path +/** The folder under the home directory where the location pickers place and look for projects. */ +internal const val IDEA_PROJECTS_DIR = "IdeaProjects" + internal fun projectLocationOptions(projectName: String, currentDir: Path, homeDir: Path): List> = listOf( "Current directory" to currentDir, "Subdirectory" to currentDir.resolve(projectName).normalize(), - "IdeaProjects" to homeDir.resolve("IdeaProjects").resolve(projectName).normalize(), + "IdeaProjects" to homeDir.resolve(IDEA_PROJECTS_DIR).resolve(projectName).normalize(), ) internal fun chooseProjectLocation( diff --git a/src/main/kotlin/io/jmix/cli/command/ToolkitCommand.kt b/src/main/kotlin/io/jmix/cli/command/ToolkitCommand.kt new file mode 100644 index 0000000..0a8e1a9 --- /dev/null +++ b/src/main/kotlin/io/jmix/cli/command/ToolkitCommand.kt @@ -0,0 +1,657 @@ +package io.jmix.cli.command + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.CliktError +import com.github.ajalt.clikt.core.Context +import com.github.ajalt.clikt.core.UsageError +import com.github.ajalt.clikt.core.context +import com.github.ajalt.clikt.core.terminal +import com.github.ajalt.clikt.output.HelpFormatter +import com.github.ajalt.clikt.output.MordantHelpFormatter +import com.github.ajalt.clikt.parameters.arguments.argument +import com.github.ajalt.clikt.parameters.arguments.multiple +import com.github.ajalt.clikt.parameters.options.flag +import com.github.ajalt.clikt.parameters.options.option +import com.github.ajalt.clikt.parameters.types.choice +import com.github.ajalt.mordant.rendering.TextColors.brightGreen +import com.github.ajalt.mordant.rendering.TextColors.brightRed +import com.github.ajalt.mordant.rendering.TextColors.cyan +import com.github.ajalt.mordant.rendering.TextColors.gray +import com.github.ajalt.mordant.rendering.TextColors.green +import com.github.ajalt.mordant.rendering.TextColors.yellow +import com.github.ajalt.mordant.rendering.TextStyle +import com.github.ajalt.mordant.rendering.TextStyles.bold +import com.github.ajalt.mordant.widgets.SelectList +import io.jmix.cli.env.AgentToolkitInstaller +import io.jmix.cli.env.AgentToolkitMetadata +import io.jmix.cli.env.AgentToolkitStatus +import io.jmix.cli.env.ToolkitChoice +import io.jmix.cli.env.ToolkitMcpOptions +import io.jmix.cli.env.ToolkitResult +import io.jmix.cli.env.ToolkitStep +import io.jmix.cli.trial.TrialArchive +import io.jmix.cli.update.SelfUpdater +import io.jmix.cli.util.describeIoError +import io.jmix.cli.util.hostOf +import io.jmix.cli.wizard.Answer +import io.jmix.cli.wizard.PathCompleter +import io.jmix.cli.wizard.Prompts +import io.jmix.cli.wizard.StatusReporter +import io.jmix.cli.wizard.WizardChoice +import io.jmix.cli.wizard.WizardUiState +import java.io.FileNotFoundException +import java.io.IOException +import java.io.UncheckedIOException +import java.nio.file.Files +import java.nio.file.InvalidPathException +import java.nio.file.Path +import java.time.Duration + +internal typealias ToolkitInstall = (Path, String, Set, List?, List?, (String) -> Unit) -> ToolkitResult +internal typealias ToolkitMcpLoader = (ref: String, timeout: Duration) -> ToolkitMcpOptions +internal typealias ToolkitStatusCheck = (projectDir: Path, ref: String) -> AgentToolkitStatus.Status? + +/** + * Adds or updates the Jmix Agent Toolkit in an existing project. The servers and agents it accepts and lists + * are the ones the toolkit publishes for the project's branch; none are named here. [install], [mcpOptions], + * [status], [currentDir] and [homeDir] let tests run it without the network, the installer or the real + * working and home directories. + */ +class ToolkitCommand internal constructor( + private val install: ToolkitInstall, + private val mcpOptions: ToolkitMcpLoader, + private val status: ToolkitStatusCheck, + private val currentDir: () -> Path = { Path.of("").toAbsolutePath().normalize() }, + private val homeDir: () -> Path = { Path.of(System.getProperty("user.home")) }, +) : CliktCommand(name = "agent-toolkit") { + + constructor() : this( + AgentToolkitInstaller::install, AgentToolkitMetadata::mcpOptions, { dir, ref -> AgentToolkitStatus.detect(dir, ref) }, + ) + + init { + // Not helpEpilog: Clikt evaluates it for every usage error, and only printed help may ask the toolkit. + context { + val inherited = helpFormatter ?: { MordantHelpFormatter(it) } + helpFormatter = { ctx -> + val formatter = inherited(ctx) + object : HelpFormatter { + override fun formatHelp( + error: UsageError?, + prolog: String, + epilog: String, + parameters: List, + programName: String, + ) = formatter.formatHelp(error, prolog, if (error == null) offeredChoices() else epilog, parameters, programName) + } + } + } + } + + // The command menu shows it beside the name: kept short so the menu fits 80 columns (MainTest). + override fun help(context: Context) = "Add or update AI Agent Toolkit: skills, guidelines, MCP" + + private val stepArgs by argument( + "steps", help = "Steps to run: skills, guidelines, mcp (default: ask; all three with --non-interactive)", + ).choice(STEP_IDS).multiple() + private val path by option("--path", help = "Project directory (default: ask; current directory with --non-interactive)") + private val jmixVersion by option( + "--jmix-version", help = "Jmix version of the project (default: detected from the build file)", + ) + private val servers by option( + "--servers", help = "MCP servers to configure, comma-separated (default: all the toolkit offers)", + ) + private val agents by option( + "--agents", help = "AI agents to configure, comma-separated (default: all the toolkit offers)", + ) + private val nonInteractive by option("--non-interactive", help = "Never prompt; use arguments and defaults").flag() + + // Acted on in main(), before parsing; declared so the parser accepts it after the command name. + @Suppress("unused") + private val noUpdate by option(SelfUpdater.NO_UPDATE_FLAG, help = "Skip the startup update check").flag() + + /** In the order they are resolved; a later one depends on the earlier ones. */ + private enum class Step { DIRECTORY, VERSION, STEPS, SERVERS, AGENTS } + + /** ASK: the step has a question, and questions are not open yet (see [asking]). */ + private enum class Outcome { PROMPTED, AUTO, BACK, ASK } + + /** + * What the steps resolved so far. [status] is the state of [dir] for [branch], detected once; + * [options] is the metadata of [branch]; the two lists are set when [steps] has the MCP step. + */ + private data class Answers( + val dir: Path? = null, + val version: String? = null, + val branch: String? = null, + val status: AgentToolkitStatus.Status? = null, + val steps: Set? = null, + val options: ToolkitMcpOptions? = null, + val servers: List? = null, + val agents: List? = null, + ) + + private lateinit var reporter: StatusReporter + private lateinit var prompts: Prompts + private var answers = Answers() + + /** Off while the steps that need no question are resolved; the first question turns it on. */ + private var asking = false + + /** The questions answered before the current step: Back returns to the last one, and the summary lists them. */ + private var asked = emptyList() + private var printedProject: WizardChoice? = null + + /** The projects found nearby, looked for once per run. */ + private var projectList: List? = null + + override fun run() { + answers = Answers() + asking = false + asked = emptyList() + printedProject = null + projectList = null + reporter = StatusReporter(terminal) + // A script or an agent without --non-interactive must not end with exit code 0 and nothing done. + prompts = Prompts(terminal, exitOnEof = true, eofError = NO_INPUT) { WizardUiState(choices()) } + rejectMcpOptionsWithout(stepArgs.toSet()) + // Before any question: the option needs no project, so a malformed one fails before the project list. + jmixVersion?.let(::branchOf) + val result = try { + // Resolved before anything is written: the installer gets explicit, offered ids for the MCP step. + // The alternate screen opens for the first question; a run that asks nothing stays on the main one. + val firstQuestion = resolve(0) + val restate = firstQuestion < Step.entries.size && prompts.useAlternateScreen { + asking = true + resolve(firstQuestion) + } + // The frames lived on the alternate screen, which the terminal has just discarded. + if (restate) choices().forEach(::printChoice) else printProject() + val setup = answers + val steps = checkNotNull(setup.steps) + if (steps.isEmpty()) { + terminal.println(NOTHING_SELECTED) + return + } + if (asked.isNotEmpty()) terminal.println() + reporter.run("Setting up the Agent Toolkit") { progress -> + install(checkNotNull(setup.dir), checkNotNull(setup.version), steps, setup.servers, setup.agents, progress::relabel) + } + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + throw CliktError("Agent Toolkit setup was interrupted.") + } catch (e: IOException) { + // A failed step ends with the installer's own output, which is external text. + val cause = describeIoError(e, hostOf(AgentToolkitInstaller.RAW_CONTENT_BASE)).filterNot(Char::isISOControl) + throw CliktError("Agent Toolkit setup failed: $cause") + } + printResult(checkNotNull(answers.branch), checkNotNull(answers.steps), result) + } + + /** + * Resolves every step from its argument or option, else by asking; a scripted run takes the default or fails. + * Back returns to the previous question that was asked, and from the first one to the command menu. + * Starts at step [from]; returns the step that has a question while [asking] is off, else the number of steps. + */ + private fun resolve(from: Int): Int { + var index = from + while (index < Step.entries.size) { + val step = Step.entries[index] + asked = asked.filter { it < step } + val outcome = when (step) { + Step.DIRECTORY -> stepDirectory() + Step.VERSION -> stepVersion() + Step.STEPS -> stepSteps() + Step.SERVERS -> stepServers() + Step.AGENTS -> stepAgents() + } + if (outcome == Outcome.ASK) return index + if (outcome == Outcome.BACK) { + index = (asked.lastOrNull() ?: throw ReturnToMainMenu()).ordinal + continue + } + if (outcome == Outcome.PROMPTED) { + asked = asked + step + if (!prompts.isAlternateScreenHeld) answer(step)?.let(::printChoice) + } + index++ + } + return index + } + + /** `--path`, else the current directory in a scripted run; an interactive run always asks which project. */ + private fun stepDirectory(): Outcome { + val previous = answers.dir + answers = Answers() + // Text that is no path is no project either; it is printed without its control characters. + val given = path?.let { typedDir(it) ?: throw noProject(it) } ?: currentDir().takeIf { nonInteractive } + if (given != null) { + if (!isGradleProject(given)) throw noProject("$given") + answers = answers.copy(dir = given) + return Outcome.AUTO + } + if (!asking) return Outcome.ASK + answers = answers.copy(dir = chooseProjectDir(previous) ?: return Outcome.BACK) + return Outcome.PROMPTED + } + + /** + * The current directory when it is a Gradle project, the Jmix projects one level below it and in + * ~/IdeaProjects, or a typed directory; [previous] is preselected. Null for Back. Back from the typed + * directory shows the list again with Other... selected, unless Other... is the only entry: then the + * list was never shown, and Back leaves the question. + */ + private fun chooseProjectDir(previous: Path?): Path? { + val found = projectList ?: reporter.run("Looking for Jmix projects") { projectOptions() }.also { projectList = it } + val options = found + ProjectOption(OTHER_CHOICE, null) + val listed = options.indexOfFirst { previous != null && it.dir == previous } + val typedBefore = previous?.takeIf { listed < 0 } + var defaultIndex = if (typedBefore != null) options.lastIndex else listed.coerceAtLeast(0) + while (true) { + val option = when (val picked = prompts.choose( + "Select project directory", options, { it.title }, { it.description }, defaultIndex, allowBack = true, + )) { + is Answer.Back -> return null + is Answer.Value -> picked.value + } + option.dir?.let { return it } + val typed = prompts.ask( + "Enter project directory", typedBefore?.toString(), allowBack = true, complete = { PathCompleter.complete(it) }, + ) { + val dir = typedDir(it) + when { + it.isBlank() -> "Path cannot be empty." + dir != null && isGradleProject(dir) -> null + else -> "No Gradle project found in ${shown(dir ?: it)}." + } + } + when (typed) { + is Answer.Value -> return typedDir(typed.value) + is Answer.Back -> if (options.size == 1) return null else defaultIndex = options.lastIndex + } + } + } + + private fun projectOptions(): List { + val cwd = currentDir() + val home = homeDir() + val current = listOfNotNull(cwd.takeIf(::isGradleProject)?.let { ProjectOption(CURRENT_DIRECTORY, it, versionOrNull(it)) }) + // Not the folders of the home directory itself: on macOS, looking into Desktop or Documents asks for access. + val parents = listOfNotNull(cwd.takeIf { realOrSelf(it) != realOrSelf(home) }, home.resolve(IDEA_PROJECTS_DIR)) + val nearby = parents + .flatMap(::childProjects) + .distinctBy(::realOrSelf) + .filter { realOrSelf(it) != realOrSelf(cwd) } + .mapNotNull { dir -> versionOrNull(dir)?.let { ProjectOption(dir.fileName.toString(), dir, it) } } + .sortedBy { it.title.lowercase() } + return current + nearby + } + + /** The Gradle projects directly inside [parent], hidden folders and odd names aside; none when it cannot be listed. */ + private fun childProjects(parent: Path): List = try { + Files.list(parent).use { entries -> + entries.filter { child -> + val name = child.fileName.toString() + !name.startsWith(".") && name.none(Char::isISOControl) && Files.isDirectory(child) && isGradleProject(child) + }.toList() + } + } catch (e: IOException) { + emptyList() + } catch (e: UncheckedIOException) { + emptyList() + } + + /** A folder the list cannot read is listed without a version, or not at all when only the version admits it. */ + private fun versionOrNull(dir: Path): String? = try { + detectedVersion(dir) + } catch (e: IOException) { + null + } + + private fun realOrSelf(path: Path): Path = try { + path.toRealPath() + } catch (e: IOException) { + path + } + + /** An entry of the project list; [dir] is null for Other.... */ + private class ProjectOption(val title: String, val dir: Path?, version: String? = null) { + val description: String? = dir?.let { shown(it) + version?.let { v -> " (Jmix $v)" }.orEmpty() } + } + + private fun stepVersion(): Outcome { + val dir = checkNotNull(answers.dir) + // Back to this question offers the version typed before; a project chosen again has none. + val typedBefore = answers.version + answers = Answers(dir = dir) + val known = jmixVersion ?: detectedVersion(dir) + if (known != null) { + answers = answers.copy(version = known, branch = branchOf(known)) + return Outcome.AUTO + } + if (nonInteractive) throw CliktError("Cannot detect the Jmix version in ${shown(dir)}. Pass --jmix-version.") + if (!asking) return Outcome.ASK + printProject() + val typed = prompts.ask("Jmix version of the project", typedBefore, allowBack = true) { + if (branchOrNull(it) == null) "Enter a Jmix version such as 3.1.0." else null + } + return when (typed) { + is Answer.Back -> Outcome.BACK + is Answer.Value -> { + answers = answers.copy(version = typed.value, branch = branchOrNull(typed.value)) + Outcome.PROMPTED + } + } + } + + /** The steps the arguments name, else all of them in a scripted run; an interactive run asks. */ + private fun stepSteps(): Outcome { + val given = stepArgs.toSet().ifEmpty { null } ?: ToolkitStep.entries.toSet().takeIf { nonInteractive } + val chosen = given ?: run { + if (!asking) return Outcome.ASK + printProject() + when (val picked = askSteps()) { + is Answer.Back -> return Outcome.BACK + is Answer.Value -> picked.value + } + } + // The MCP lists chosen before are offered again while the MCP step stays chosen, and dropped without it. + val mcp = ToolkitStep.MCP in chosen + answers = answers.copy(steps = chosen, servers = answers.servers.takeIf { mcp }, agents = answers.agents.takeIf { mcp }) + return if (given == null) Outcome.PROMPTED else Outcome.AUTO + } + + /** + * A checklist of the steps with the state of each. A step that is up to date starts unchecked, one whose + * state is unknown starts checked, and Back to it keeps the earlier choice. MCP stays checked when + * `--servers` or `--agents` is given. An empty choice is allowed: it runs nothing. + */ + private fun askSteps(): Answer> { + // The MCP questions reuse the metadata the status was found with. + val status = answers.status ?: detectStatus().also { answers = answers.copy(status = it, options = it.mcpOptions) } + val states = mapOf(ToolkitStep.SKILLS to status.skills, ToolkitStep.GUIDELINES to status.guidelines, ToolkitStep.MCP to status.mcp) + val steps = ToolkitStep.entries + val ids = steps.map(::stepId) + val width = ids.maxOf { it.length } + val locked = setOfNotNull(steps.indexOf(ToolkitStep.MCP).takeIf { servers != null || agents != null }) + val entries = steps.mapIndexed { index, step -> + val state = states[step] + val hint = state?.let { " · " + STATUS_HINTS.getValue(it) }.orEmpty() + val selected = index in locked || (answers.steps?.let { step in it } ?: (state != AgentToolkitStatus.State.UP_TO_DATE)) + SelectList.Entry(ids[index].padEnd(width) + gray(" — " + STEP_HELP.getValue(step) + hint), selected = selected) + } + val legend = ALL_UP_TO_DATE.takeIf { entries.none { it.selected } } + val picked = prompts.chooseMany(STEPS_QUESTION, entries, allowBack = true, lockedIndices = locked, values = ids, legend = legend) + // Without raw mode only a searchable list falls back to a numbered checklist. + ?: checkNotNull(prompts.chooseMany( + STEPS_QUESTION, entries, allowBack = true, filterTexts = ids, lockedIndices = locked, values = ids, legend = legend, + )) + return when (picked) { + is Answer.Back -> Answer.Back + is Answer.Value -> Answer.Value(steps.filter { stepId(it) in picked.value }.toSet()) + } + } + + /** The state of each step in the project; unknown when the toolkit gives no answer. */ + private fun detectStatus(): AgentToolkitStatus.Status { + val dir = checkNotNull(answers.dir) + val branch = checkNotNull(answers.branch) + return try { + reporter.run("Checking the Agent Toolkit") { status(dir, branch) } + } catch (e: Exception) { + if (e is InterruptedException) Thread.currentThread().interrupt() + null + } ?: UNKNOWN_STATUS + } + + private fun stepServers(): Outcome { + val setup = answers + if (ToolkitStep.MCP !in checkNotNull(setup.steps)) return Outcome.AUTO + val options = setup.options ?: loadMcpOptions(checkNotNull(setup.branch), checkNotNull(setup.version)) + answers = setup.copy(options = options) + return stepSelection(servers, options.servers, setup.servers, "MCP server") { answers = answers.copy(servers = it) } + } + + private fun stepAgents(): Outcome { + val setup = answers + if (ToolkitStep.MCP !in checkNotNull(setup.steps)) return Outcome.AUTO + return stepSelection(agents, checkNotNull(setup.options).agents, setup.agents, "AI agent") { answers = answers.copy(agents = it) } + } + + /** + * One MCP list: what its option names, else every offered id in a scripted run; an interactive run asks. + * [previous] is the earlier answer, kept when Back returns to the question. + */ + private fun stepSelection( + raw: String?, offered: List, previous: List?, kind: String, store: (List) -> Unit, + ): Outcome { + if (raw != null || nonInteractive) { + store(selection(raw, offered, kind)) + return Outcome.AUTO + } + if (!asking) return Outcome.ASK + printProject() + return when (val picked = askSelection(offered, previous, kind)) { + is Answer.Back -> Outcome.BACK + is Answer.Value -> { + store(picked.value) + Outcome.PROMPTED + } + } + } + + /** + * A checklist of the toolkit's labels with [previous] checked, or every entry when there is none; a console + * without raw mode gets one text question in the option's syntax. + */ + private fun askSelection(offered: List, previous: List?, kind: String): Answer> { + val ids = offered.map { it.value } + val entries = offered.map { SelectList.Entry(it.label, selected = previous?.contains(it.value) ?: true) } + var legend: String? = null + while (true) { + val picked = prompts.chooseMany("Select ${kind}s", entries, allowBack = true, values = ids, legend = legend) + ?: return askSelectionLine(ids, previous ?: ids, kind) + // An empty pick is the one mistake a checklist allows; the question repeats with the reason above it. + val error = (picked as? Answer.Value)?.let { selectionError(it.value.joinToString(","), ids, kind) } + ?: return picked + legend = brightRed(error) + } + } + + private fun askSelectionLine(ids: List, default: List, kind: String): Answer> { + val typed = prompts.ask("${kind}s", default.joinToString(","), allowBack = true) { selectionError(it, ids, kind) } + return when (typed) { + is Answer.Back -> Answer.Back + is Answer.Value -> Answer.Value(parseSelection(typed.value, ids)) + } + } + + private fun rejectMcpOptionsWithout(steps: Set) { + if (steps.isNotEmpty() && ToolkitStep.MCP !in steps && (servers != null || agents != null)) { + throw CliktError("--servers and --agents apply only to the mcp step.") + } + } + + private fun isGradleProject(dir: Path) = GRADLE_FILES.any { Files.isRegularFile(dir.resolve(it)) } + + /** [dir] can be text that is no path at all; it is printed without its control characters. */ + private fun noProject(dir: String) = + CliktError("No Gradle project found in ${shown(dir)}. Run `jmix agent-toolkit` from the project root or pass --path.") + + /** The directory that typed text names; null when it is no path at all. */ + private fun typedDir(raw: String): Path? = try { + toAbsolutePath(raw) + } catch (e: InvalidPathException) { + null + } + + /** The version in the build files of [dir]; one that names no toolkit branch counts as not detected. */ + private fun detectedVersion(dir: Path): String? = TrialArchive.jmixVersion(dir)?.takeIf { branchOrNull(it) != null } + + private fun branchOrNull(version: String): String? = try { + AgentToolkitInstaller.branch(version) + } catch (e: IOException) { + null + } + + /** The toolkit branch of [version]; a version that names none fails the command. */ + private fun branchOf(version: String): String = try { + AgentToolkitInstaller.branch(version) + } catch (e: IOException) { + throw CliktError(e.message?.let(::shown)) + } + + private fun loadMcpOptions(branch: String, version: String): ToolkitMcpOptions = try { + reporter.run("Loading the Agent Toolkit metadata") { mcpOptions(branch, METADATA_TIMEOUT) } + } catch (e: FileNotFoundException) { + throw IOException(AgentToolkitInstaller.missingBranchMessage(version)) + } + + /** The ids of [offered] that [raw] names; all of them without the option. */ + private fun selection(raw: String?, offered: List, kind: String): List { + val valid = offered.map { it.value } + if (raw == null) return valid + selectionError(raw, valid, kind)?.let { throw CliktError(it) } + return parseSelection(raw, valid) + } + + /** The project with its version and branch once they are known; before that the directory alone. */ + private fun project(): WizardChoice? = with(answers) { + dir?.let { WizardChoice("Project", shown(it) + branch?.let { b -> " (Jmix ${shown(version.orEmpty())}, toolkit $b)" }.orEmpty()) } + } + + /** The summary line of a question; the directory and the version are in the project line. */ + private fun answer(step: Step): WizardChoice? = when (step) { + Step.DIRECTORY, Step.VERSION -> null + Step.STEPS -> answers.steps?.ifEmpty { null }?.let { WizardChoice("Steps", it.sorted().joinToString(", ", transform = ::stepId)) } + Step.SERVERS -> answers.servers?.let { WizardChoice("MCP servers", it.joinToString(", ")) } + Step.AGENTS -> answers.agents?.let { WizardChoice("AI agents", it.joinToString(", ")) } + } + + private fun choices(): List = listOfNotNull(project()) + asked.mapNotNull(::answer) + + private fun printChoice(choice: WizardChoice) = + terminal.println(brightGreen("✓ ") + choice.label + ":" + cyan(" ${choice.value}")) + + /** + * Prints the project line above the first question that follows it, else above the run, and again only + * when Back changed the project. A failure before either prints none. A held screen draws it in its frames. + */ + private fun printProject() { + val project = project() + if (project == null || project == printedProject || prompts.isAlternateScreenHeld) return + printChoice(project) + printedProject = project + } + + /** The headline speaks for the [steps] that ran: a run of some of them says nothing about the others. */ + private fun printResult(branch: String, steps: Set, result: ToolkitResult) { + val unchanged = result.changes.isEmpty() + val headline = if (steps == ToolkitStep.entries.toSet()) { + "Agent Toolkit $branch " + if (unchanged) "is already up to date" else "is set up" + } else { + val names = ToolkitStep.entries.filter { it in steps }.joinToString(", ", transform = ::stepId) + "Agent Toolkit $branch: $names " + if (unchanged) "already up to date" else "set up" + } + terminal.println(brightGreen("✓ $headline")) + val width = maxOf(MIN_ACTION_WIDTH, result.changes.maxOfOrNull { it.action.length } ?: 0) + for (change in result.changes) { + val action = change.action.padEnd(width) + terminal.println(" " + (ACTION_STYLES[change.action]?.invoke(action) ?: action) + " " + change.path) + } + if (result.notes.isNotEmpty()) { + terminal.println() + terminal.println(bold("Notes from the Agent Toolkit:")) + val width = noteWidth() + result.notes.forEach { printNote(it, width) } + } + } + + /** + * The width a terminal breaks notes at, under their bullet. Null for piped output, which keeps one line per + * note for scripts, and for a terminal that reports no size. + */ + private fun noteWidth(): Int? { + if (!terminal.terminalInfo.outputInteractive) return null + terminal.updateSize() + val columns = terminal.size.width + return if (columns > 0) (columns - 1 - NOTE_BULLET.length).coerceAtLeast(MIN_NOTE_WIDTH) else null + } + + private fun printNote(note: String, width: Int?) { + val lines = width?.let { wrapWords(note, it) } ?: listOf(note) + lines.forEachIndexed { index, line -> terminal.println((if (index == 0) NOTE_BULLET else NOTE_INDENT) + line) } + } + + /** The last paragraph of the help: what the toolkit offers now, for the project in the current directory if any. */ + private fun offeredChoices(): String = try { + val ref = detectedVersion(currentDir())?.let(::branchOrNull) ?: DEFAULT_REF + val options = mcpOptions(ref, HELP_TIMEOUT) + val toolkit = if (ref == DEFAULT_REF) "Agent Toolkit" else "Agent Toolkit $ref" + "MCP servers in $toolkit: ${options.servers.joinToString(", ") { it.value }}. " + + "AI agents: ${options.agents.joinToString(", ") { it.value }}." + } catch (e: Exception) { + if (e is InterruptedException) Thread.currentThread().interrupt() + "The current MCP servers and AI agents are listed when the Agent Toolkit is reachable." + } + + private companion object { + val STEP_IDS: Map = ToolkitStep.entries.associateBy(::stepId) + val STEP_HELP = mapOf( + ToolkitStep.SKILLS to "Update agent skills", + ToolkitStep.GUIDELINES to "Generate AGENTS.md guidelines", + ToolkitStep.MCP to "Configure MCP servers", + ) + const val STEPS_QUESTION = "What would you like to set up?" + const val ALL_UP_TO_DATE = "Everything is up to date. Select a step to run it anyway." + const val NOTHING_SELECTED = "Nothing selected, so nothing was changed." + val UNKNOWN_STATUS = AgentToolkitStatus.Status(null, null, null) + val STATUS_HINTS = mapOf( + AgentToolkitStatus.State.NOT_INSTALLED to "not installed", + AgentToolkitStatus.State.UP_TO_DATE to green("up to date"), + AgentToolkitStatus.State.UPDATE_AVAILABLE to yellow("update available"), + ) + val GRADLE_FILES = listOf("build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts") + val ACTION_STYLES = mapOf("created" to green, "updated" to cyan, "backed-up" to yellow) + val MIN_ACTION_WIDTH = ACTION_STYLES.keys.maxOf { it.length } + const val NOTE_BULLET = " • " + const val NOTE_INDENT = " " + const val MIN_NOTE_WIDTH = 20 + const val DEFAULT_REF = "HEAD" + const val CURRENT_DIRECTORY = "Current directory" + const val OTHER_CHOICE = "Other..." + const val NO_INPUT = "No input to answer the questions, so nothing was set up. " + + "Use --non-interactive, or pass the answers as arguments and options." + val METADATA_TIMEOUT: Duration = Duration.ofSeconds(15) + val HELP_TIMEOUT: Duration = Duration.ofSeconds(3) + } +} + +/** The word for [step] on the command line and in the summary. */ +private fun stepId(step: ToolkitStep): String = step.name.lowercase() + +/** The values of [valid] that [raw] names, in the order of [valid]. */ +private fun parseSelection(raw: String, valid: List): List { + val named = selectionValues(raw) + return valid.filter { it.lowercase() in named } +} + +/** Null when [raw] is a non-empty comma-separated subset of [valid]; else the message. [kind] is "MCP server" or "AI agent". */ +private fun selectionError(raw: String, valid: List, kind: String): String? { + val named = selectionValues(raw) + if (named.isEmpty()) return "Select at least one $kind." + val unknown = named.firstOrNull { name -> valid.none { it.lowercase() == name } } ?: return null + return "Unknown $kind: $unknown. Valid values: ${valid.joinToString(", ")}." +} + +private fun selectionValues(raw: String): List = raw.split(',').map { it.trim().lowercase() }.filter { it.isNotEmpty() } + +/** Paths and names from the disk or the command line, printed without their control characters. */ +private fun shown(text: Any): String = "$text".filterNot(Char::isISOControl) + +/** [text] in lines of at most [width] characters, broken at spaces; a longer word gets a line of its own. */ +internal fun wrapWords(text: String, width: Int): List = + text.split(' ').filter(String::isNotEmpty).fold(emptyList()) { lines, word -> + val last = lines.lastOrNull() + if (last != null && last.length + 1 + word.length <= width) lines.dropLast(1) + "$last $word" else lines + word + } diff --git a/src/main/kotlin/io/jmix/cli/command/TrialCommand.kt b/src/main/kotlin/io/jmix/cli/command/TrialCommand.kt index 3c33ea4..0ea5cab 100644 --- a/src/main/kotlin/io/jmix/cli/command/TrialCommand.kt +++ b/src/main/kotlin/io/jmix/cli/command/TrialCommand.kt @@ -47,7 +47,7 @@ internal class TrialCommand( private val usageStatistics: UsageStatistics? = null, ) : CliktCommand(name = "trial") { - override fun help(context: Context) = "Download the Enterprise+BPM trial project of your Jmix account" + override fun help(context: Context) = "Download the Enterprise+BPM trial of your Jmix account" private val path by option( "--path", help = "Initial parent directory for the trial project (non-interactive default: current directory)", diff --git a/src/main/kotlin/io/jmix/cli/command/UpdateCommand.kt b/src/main/kotlin/io/jmix/cli/command/UpdateCommand.kt index 4eca4e4..ee7abc0 100644 --- a/src/main/kotlin/io/jmix/cli/command/UpdateCommand.kt +++ b/src/main/kotlin/io/jmix/cli/command/UpdateCommand.kt @@ -15,7 +15,7 @@ import io.jmix.cli.wizard.StatusReporter class UpdateCommand : CliktCommand(name = "update") { - override fun help(context: Context) = "Update Jmix CLI to the latest release and remove old versions" + override fun help(context: Context) = "Update Jmix CLI and remove old versions" // Accepted for symmetry with the other commands; `jmix update` never runs // the startup check anyway. diff --git a/src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt b/src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt index 05e6540..3c4838e 100644 --- a/src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt +++ b/src/main/kotlin/io/jmix/cli/env/AgentToolkitInstaller.kt @@ -1,28 +1,44 @@ package io.jmix.cli.env +import io.jmix.cli.WindowsConsole import io.jmix.cli.util.Http import io.jmix.cli.util.hostOf +import java.io.File import java.io.IOException +import java.io.UncheckedIOException import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.Charset import java.nio.file.Files +import java.nio.file.InvalidPathException import java.nio.file.LinkOption.NOFOLLOW_LINKS import java.nio.file.Path import java.time.Duration import java.util.concurrent.TimeUnit +enum class ToolkitStep { SKILLS, GUIDELINES, MCP } + +/** [action] is the toolkit's word, such as created, updated or backed-up; [path] is relative to the project with `/` separators when inside it. */ +data class ToolkitChange(val action: String, val path: String) + +/** [notes] are the toolkit's own guidance lines. */ +data class ToolkitResult(val changes: List, val notes: List) + /** * Installs the Jmix Agent Toolkit - * (https://github.com/jmix-framework/jmix-agent-toolkit) into a generated + * (https://github.com/jmix-framework/jmix-agent-toolkit) into a * project: shared guidelines, local skills, and project MCP configuration. - * The downloaded script runs from a file with a fixed argument list. + * The downloaded script runs from a file with a complete argument list, never through a shell string. */ object AgentToolkitInstaller { /** Toolkit branch for a Jmix version; majors are the only accepted shape. */ fun branch(jmixVersion: String): String { - val major = jmixVersion.substringBefore('.').toIntOrNull() + // ASCII digits only: toIntOrNull alone also takes a sign and the digits of other scripts. + val major = jmixVersion.substringBefore('.').takeIf { it.all { digit -> digit in '0'..'9' } }?.toIntOrNull() ?: throw IOException("Unexpected Jmix version format: $jmixVersion") return "v$major" } @@ -41,71 +57,313 @@ object AgentToolkitInstaller { fun guidelinesArgs(): List = listOf("agents-md") - internal fun mcpArgs(os: String = System.getProperty("os.name")): List = + internal fun mcpArgs(servers: List, agents: List, os: String = System.getProperty("os.name")): List = if (isWindows(os)) { - listOf("mcp", "-Servers", MCP_SERVERS, "-Agents", MCP_AGENTS, "-Scope", "local") + listOf("mcp", "-Servers", servers.joinToString(","), "-Agents", agents.joinToString(","), "-Scope", "local") } else { - listOf("mcp", "--servers", MCP_SERVERS, "--agents", MCP_AGENTS, "--scope", "local") + listOf("mcp", "--servers", servers.joinToString(","), "--agents", agents.joinToString(","), "--scope", "local") } + /** "the toolkit has no v4 branch for Jmix 4 yet" for [jmixVersion] 4.x. */ + internal fun missingBranchMessage(jmixVersion: String): String { + val branch = branch(jmixVersion) + return "the toolkit has no $branch branch for Jmix ${branch.removePrefix("v")} yet" + } + fun command(scriptFile: Path, args: List, os: String = System.getProperty("os.name")): List = if (isWindows(os)) { - listOf("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", scriptFile.toString()) + args + // The absolute path: Windows looks for a bare name in the current directory, the project, first. + val powershell = "${System.getenv("SystemRoot") ?: "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" + listOf(powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", scriptFile.toString()) + args } else { - listOf("bash", scriptFile.toString()) + args + listOf(bash, scriptFile.toString()) + args + } + + /** + * PATH without empty or relative entries. Steps run in the project, so such entries would let the + * project's own files stand in for the programs the installer calls. + */ + internal fun trustedPath(path: String?): String = + path.orEmpty().split(File.pathSeparator) + // bash expands a leading ~ in a PATH entry; the real home keeps such an entry working. + .map { entry -> if (entry == "~" || entry.startsWith("~/")) System.getProperty("user.home") + entry.drop(1) else entry } + .filter { entry -> entry.isNotEmpty() && runCatching { Path.of(entry).isAbsolute }.getOrDefault(false) } + .joinToString(File.pathSeparator) + + /** + * Applies [trustedPath] to the PATH variable in any letter case: Windows names it Path, and the map is + * case-sensitive. Outside Windows a missing or emptied PATH becomes [FALLBACK_PATH]: bash looks a command up + * in the current directory, the project, when PATH is empty, and its built-in default ends with `.`. + */ + internal fun trustPathVariable(environment: MutableMap, os: String = System.getProperty("os.name")) { + val keys = environment.keys.filter { it.equals("PATH", ignoreCase = true) } + keys.forEach { key -> environment[key] = trustedPath(environment[key]) } + if (!isWindows(os) && keys.all { environment[it].isNullOrEmpty() }) { + keys.forEach(environment::remove) + environment["PATH"] = FALLBACK_PATH } + } /** - * Installs the Toolkit into [projectDir]. + * The environment of a step, changed in place: change markers on, a trusted PATH, no inherited + * PSModulePath, and for the MCP step ([mcpProfile]) Claude Desktop's user profile moved to that folder. + */ + internal fun prepareEnvironment(environment: MutableMap, mcpProfile: Path?, os: String = System.getProperty("os.name")) { + // A pwsh-flavored PSModulePath inherited from the parent (pwsh + // terminals, GitHub Actions) breaks Windows PowerShell 5.1 module + // autoloading (Get-FileHash etc.); let the shell rebuild its own. + environment.remove("PSModulePath") + environment["JMIX_EMIT_CHANGE_MARKERS"] = "1" + trustPathVariable(environment, os) + if (mcpProfile != null) isolateClaudeDesktop(environment, mcpProfile, os) + } + + /** bash by its absolute path: the JVM looks a bare name up in PATH entries that resolve inside the project. */ + private val bash: String by lazy { + trustedPath(System.getenv("PATH")).split(File.pathSeparator).filter { it.isNotEmpty() } + .map { Path.of(it, "bash") } + .firstOrNull { Files.isRegularFile(it) && Files.isExecutable(it) } + ?.toString() ?: "/bin/bash" + } + + /** + * Runs the selected [steps] of the Toolkit in [projectDir], in the order skills, guidelines, MCP. + * [servers] and [agents] apply to the MCP step; null means every choice the toolkit metadata offers. + * They are passed to the installer unchecked, so they must be ids that metadata offers ([AgentToolkitMetadata.mcpOptions]). * [onStatus] names each phase before it starts, for a progress indicator. + * The link guard ([rejectLinkedPaths]) runs for all selected steps before anything is downloaded or written. */ - fun install(projectDir: Path, jmixVersion: String, onStatus: (String) -> Unit = {}) { + fun install( + projectDir: Path, + jmixVersion: String, + steps: Set = ToolkitStep.entries.toSet(), + servers: List? = null, + agents: List? = null, + onStatus: (String) -> Unit = {}, + ): ToolkitResult { + val branch = branch(jmixVersion) + val root = projectDir.toRealPath() + rejectLinkedPaths(root, steps) val suffix = if (isWindows()) ".ps1" else ".sh" val script = Files.createTempFile("jmix-agent-toolkit", suffix) try { val url = installerUrl(jmixVersion) onStatus("Downloading the Agent Toolkit installer from ${hostOf(url)}") - download(url, script) - onStatus("Installing Agent Toolkit project-local skills") - runStep(projectDir, command(script, skillsArgs()), "skills") - onStatus("Installing Agent Toolkit shared guidelines") - runStep(projectDir, command(script, guidelinesArgs()), "guidelines") - onStatus("Configuring project MCP servers") - installProjectMcp(projectDir, script) + download(url, script, jmixVersion) + // Everything a step needs is loaded before the first one runs, so a run never stops halfway for it. + val mcpStepArgs = when { + ToolkitStep.MCP !in steps -> null + servers != null && agents != null -> mcpArgs(servers, agents) + else -> { + onStatus("Loading the Agent Toolkit metadata from ${hostOf(url)}") + val options = AgentToolkitMetadata.mcpOptions(branch) + mcpArgs(servers ?: options.servers.map { it.value }, agents ?: options.agents.map { it.value }) + } + } + val skills = if (ToolkitStep.SKILLS in steps) { + onStatus("Installing Agent Toolkit project-local skills") + runStep(root, command(script, skillsArgs()), "skills") + } else { + emptyList() + } + val guidelines = if (ToolkitStep.GUIDELINES in steps) { + onStatus("Installing Agent Toolkit shared guidelines") + runStep(root, command(script, guidelinesArgs()), "guidelines") + } else { + emptyList() + } + val mcp = if (mcpStepArgs != null) { + onStatus("Configuring project MCP servers") + installProjectMcp(root, script, mcpStepArgs) + } else { + emptyList() + } + return ToolkitResult( + parseChanges(skills + guidelines + mcp, root), + toolkitNotes(skills + guidelines, mcp = false) + toolkitNotes(mcp, mcp = true), + ) } finally { Files.deleteIfExists(script) } } - private fun installProjectMcp(projectDir: Path, script: Path) { + /** + * The lines of a step's log; empty when it cannot be read, so that never fails a step that succeeded. Valid + * UTF-8 is read as UTF-8. Anything else is read in [fallback]: on Windows the OEM code page, as Windows + * PowerShell 5.1 writes in the code page of the new console Java starts it in; elsewhere bad bytes are replaced. + * UTF-8 goes first so a console set to UTF-8 (a `CodePage` of 65001 in the registry) still reads right; the + * price is rare OEM text that is also valid UTF-8, such as `сок` under code page 866, read as UTF-8. + */ + internal fun readLog(log: Path, fallback: Charset? = WindowsConsole.oemCharset): List = try { + val bytes = Files.readAllBytes(log) + val text = try { + Charsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString() + } catch (e: CharacterCodingException) { + String(bytes, fallback ?: Charsets.UTF_8) + } + text.removePrefix("").reader().readLines() + } catch (e: IOException) { + emptyList() + } + + /** The paths the toolkit reports as written, with the first action of each. */ + internal fun parseChanges(output: List, projectDir: Path): List { val root = projectDir.toRealPath() - // Toolkit writes through symlinks, so reject redirected project config paths. - for (relative in listOf( - ".mcp.json", ".codex", ".codex/config.toml", "opencode.json", - ".junie", ".junie/mcp", ".junie/mcp/mcp.json", - )) { - val path = root.resolve(relative) - if (Files.isSymbolicLink(path) || (Files.exists(path, NOFOLLOW_LINKS) && path.toRealPath() != path)) { - throw IOException("Cannot configure project MCP servers through a linked path: $relative.") + return output.filter { it.startsWith(CHANGE_MARKER) }.mapNotNull { line -> + val fields = line.split('\t').drop(1).associate { it.substringBefore('=') to it.substringAfter('=', "") } + val action = fields["action"]?.takeIf { CHANGE_ACTION.matches(it) } ?: return@mapNotNull null + val path = fields["path"]?.filterNot(Char::isISOControl)?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null + ToolkitChange(action, projectRelative(path, root)) + }.distinctBy { it.path } + } + + private fun projectRelative(path: String, root: Path): String { + val normalized = try { + Path.of(path).normalize() + } catch (e: InvalidPathException) { + return path + } + return if (normalized != root && normalized.startsWith(root)) root.relativize(normalized).joinToString("/") else path + } + + /** + * The toolkit's guidance in [output]: lines marked `Note:`, and in the MCP step ([mcp]) every line + * that starts at column 0 and is neither an `[Server MCP] Agent` heading nor a change marker. + */ + internal fun toolkitNotes(output: List, mcp: Boolean): List = + output.mapNotNull { line -> + val text = line.filterNot(Char::isISOControl).trim() + val isGuidance = mcp && line.firstOrNull()?.isWhitespace() == false && + !text.startsWith("[") && !text.startsWith(CHANGE_MARKER) + text.takeIf { it.isNotEmpty() && (it.startsWith(NOTE_PREFIX) || isGuidance) } + }.distinct() + + /** + * The toolkit writes through links, and [root] can be a project this CLI did not create. Fails when a path + * one of [steps] writes is a link out of the project, or, for an MCP config, a link at all. The toolkit itself + * links inside the project: each skill into the Claude skills folder, and it supports `CLAUDE.md -> AGENTS.md`, + * so a link, dangling or not, that stays in the project passes. + */ + internal fun rejectLinkedPaths(root: Path, steps: Set) { + val project = root.toRealPath() + if (ToolkitStep.SKILLS in steps) { + // A local skills run also tidies the `jmix*` entries of every `./skills` (Junie's old links, + // legacy backups), following links to it. Listed names stay paths: a name that is no valid text + // in the JVM's encoding still resolves to the same entry. + val agentSkills = topLevelEntries(project).filter { it.toString().startsWith(".") } + .map { it.resolve("skills") }.filter { hasToolkitEntries(project.resolve(it)) } + rejectLinksOutside(project, (SKILLS_PATHS.map(Path::of) + agentSkills).distinct(), "skills") + } + if (ToolkitStep.GUIDELINES in steps) { + // A backup goes to the first free `.bak`, `.bak1`, ..., and a dangling link there counts as free. + val backups = topLevelEntries(project) + .filter { entry -> GUIDELINES_PATHS.any { entry.toString().startsWith("$it.bak", ignoreCase = true) } } + rejectLinksOutside(project, GUIDELINES_PATHS.map(Path::of) + backups, "guidelines") + } + if (ToolkitStep.MCP in steps) { + for (relative in MCP_PATHS) { + val path = project.resolve(relative) + if (Files.isSymbolicLink(path) || (Files.exists(path, NOFOLLOW_LINKS) && !isPlainEntry(path))) { + throw IOException("Cannot configure project MCP servers through a linked path: $relative.") + } + } + } + } + + /** + * Whether the existing [path] is itself where its real path is. A Windows junction is no symbolic link to + * Java, but its real path is elsewhere. Not `toRealPath() == path`: on a case-insensitive disk the real name + * can differ in letter case alone. + */ + private fun isPlainEntry(path: Path): Boolean { + val real = path.toRealPath() + return real.parent == path.parent.toRealPath() && real.fileName.toString().equals(path.fileName.toString(), ignoreCase = true) + } + + /** The entry names in [project], sorted; a folder that fails while it is listed fails like one that cannot be opened. */ + private fun topLevelEntries(project: Path): List = try { + Files.list(project).use { entries -> entries.map { it.fileName }.sorted().toList() } + } catch (e: UncheckedIOException) { + throw e.cause ?: e + } + + /** + * Whether the folder [dir] holds an entry the toolkit tidies in `./skills`: `jmix`, `jmix-*` or `jmix.*`, + * in any letter case to be safe. A folder that cannot be listed counts, so the guard still checks it. + */ + private fun hasToolkitEntries(dir: Path): Boolean { + if (!Files.isDirectory(dir)) return false + fun isToolkitEntry(name: String) = + name.equals("jmix", ignoreCase = true) || name.startsWith("jmix-", ignoreCase = true) || + name.startsWith("jmix.", ignoreCase = true) + return try { + Files.list(dir).use { entries -> entries.anyMatch { isToolkitEntry(it.fileName.toString()) } } + } catch (e: IOException) { + true + } catch (e: UncheckedIOException) { + true + } + } + + private fun rejectLinksOutside(project: Path, paths: List, label: String) { + for (relative in paths) { + val path = project.resolve(relative) + if (!Files.exists(path, NOFOLLOW_LINKS)) continue + val inside = try { + path.toRealPath().startsWith(project) + } catch (e: IOException) { + missingTargetInside(path, project) + } + if (!inside) { + val shown = relative.joinToString("/") + throw IOException("Cannot install Agent Toolkit $label through a path linked outside the project: $shown.") } } + } + + /** + * Whether the missing target of the dangling link [link] lies in [project], where writing through the link + * would create it. The part of the target on disk is taken by its real path and must not be a link itself. + * Only leading `..` elements are allowed: after a name, one could climb out of a linked folder. + */ + private fun missingTargetInside(link: Path, project: Path): Boolean { + val target = try { + Files.readSymbolicLink(link) + } catch (e: IOException) { + return false + } catch (e: UnsupportedOperationException) { + return false + } + if (target.dropWhile { it.toString() == ".." }.any { it.toString() == ".." }) return false + return try { + val wanted = link.parent.toRealPath().resolve(target).normalize() + var onDisk = wanted + while (!Files.exists(onDisk, NOFOLLOW_LINKS)) onDisk = onDisk.parent ?: return false + // The target itself on disk is another dangling link: refused rather than followed. + onDisk != wanted && onDisk.toRealPath().resolve(onDisk.relativize(wanted)).startsWith(project) + } catch (e: IOException) { + false + } + } + + private fun installProjectMcp(root: Path, script: Path, args: List): List { val profile = Files.createTempDirectory("jmix-toolkit-mcp-profile") try { - runStep(root, command(script, mcpArgs()), "MCP", profile) + return runStep(root, command(script, args), "MCP", profile) } finally { Files.deleteIfExists(profile) } } - private fun isolateClaudeDesktop(environment: MutableMap, profile: Path) { + private fun isolateClaudeDesktop(environment: MutableMap, profile: Path, os: String) { // Toolkit checks for Claude Desktop in the user profile even with local scope. val isolatedProfile = profile.toString() when { - isWindows() -> { + isWindows(os) -> { environment["APPDATA"] = isolatedProfile environment["LOCALAPPDATA"] = isolatedProfile } - System.getProperty("os.name").startsWith("Mac", ignoreCase = true) -> { + os.startsWith("Mac", ignoreCase = true) -> { // Keep Toolkit's read-only Codex transport conflict check on the real profile. val userHome = environment["HOME"] ?: System.getProperty("user.home") environment.putIfAbsent("CODEX_HOME", Path.of(userHome, ".codex").toString()) @@ -115,19 +373,17 @@ object AgentToolkitInstaller { } } - private fun runStep(projectDir: Path, command: List, label: String, mcpProfile: Path? = null) { + internal fun runStep(projectDir: Path, command: List, label: String, mcpProfile: Path? = null): List { // A file sink instead of a pipe: no deadlock however much the step logs. val log = Files.createTempFile("jmix-agent-toolkit", ".log") try { + // No stream is inherited: Java then starts Windows PowerShell in a console of its own (CREATE_NO_WINDOW), + // whose code page readLog decodes, never in the user's console. val builder = ProcessBuilder(command) .directory(projectDir.toFile()) .redirectErrorStream(true) .redirectOutput(log.toFile()) - // A pwsh-flavored PSModulePath inherited from the parent (pwsh - // terminals, GitHub Actions) breaks Windows PowerShell 5.1 module - // autoloading (Get-FileHash etc.); let the shell rebuild its own. - builder.environment().remove("PSModulePath") - if (mcpProfile != null) isolateClaudeDesktop(builder.environment(), mcpProfile) + prepareEnvironment(builder.environment(), mcpProfile) val process = builder.start() if (!process.waitFor(STEP_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { // Wait out the kill so the log file is closed before cleanup; @@ -138,24 +394,30 @@ object AgentToolkitInstaller { if (process.exitValue() != 0) { throw IOException("Agent Toolkit $label step failed: ${logTail(log)}") } + return readLog(log) } finally { Files.deleteIfExists(log) } } - private fun logTail(log: Path): String = try { - Files.readAllLines(log).takeLast(12).joinToString(" ") { it.trim() } - .trim().take(700).ifEmpty { "no output" } - } catch (e: IOException) { - "no output" + /** + * What a failed step said, for the error line: its `error:` lines, as both installers mark errors and the MCP + * step goes on after one, else the end of its output. External text, so control characters go. + */ + internal fun logTail(log: Path): String { + val lines = readLog(log).map { it.filterNot(Char::isISOControl).trim() } + .filter { it.isNotEmpty() && !it.startsWith(CHANGE_MARKER) } + return lines.filter { it.startsWith(ERROR_PREFIX) }.ifEmpty { lines.takeLast(TAIL_LINES) } + .joinToString(" ").take(700).ifEmpty { "no output" } } - private fun download(url: String, target: Path) { + private fun download(url: String, target: Path, jmixVersion: String) { val response = Http.sendBytes( http, HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(30)).GET().build(), MAX_INSTALLER_BYTES, ) + if (response.statusCode() == 404) throw IOException(missingBranchMessage(jmixVersion)) if (response.statusCode() != 200) { throw IOException("Failed to download the Agent Toolkit installer ($url): HTTP ${response.statusCode()}") } @@ -169,10 +431,24 @@ object AgentToolkitInstaller { .connectTimeout(Duration.ofSeconds(15)) .build() + // The project paths each step writes: safety guards that must work without the network, and so the one + // place where the toolkit's file names are repeated. + private val SKILLS_PATHS = listOf( + ".agents", ".agents/skills", ".agents/.jmix", ".agents/.jmix/backups", ".claude", ".claude/skills", + ) + private val GUIDELINES_PATHS = listOf("AGENTS.md", "CLAUDE.md") + internal val MCP_PATHS = listOf( + ".mcp.json", ".codex", ".codex/config.toml", "opencode.json", + ".junie", ".junie/mcp", ".junie/mcp/mcp.json", + ) + private const val FALLBACK_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" private const val STEP_TIMEOUT_MINUTES = 10L + private const val TAIL_LINES = 12 private const val MAX_INSTALLER_BYTES = 2 * 1024 * 1024 - private const val MCP_SERVERS = "jetbrains,jmix-docs,playwright" - private const val MCP_AGENTS = "claude,codex,opencode,junie" - private const val RAW_CONTENT_BASE = + private const val CHANGE_MARKER = "@@JMIX_CHANGE@@" + private const val NOTE_PREFIX = "Note:" + private const val ERROR_PREFIX = "error:" + private val CHANGE_ACTION = Regex("[A-Za-z0-9_-]+") + internal const val RAW_CONTENT_BASE = "https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit" } diff --git a/src/main/kotlin/io/jmix/cli/env/AgentToolkitMetadata.kt b/src/main/kotlin/io/jmix/cli/env/AgentToolkitMetadata.kt new file mode 100644 index 0000000..b9eee8b --- /dev/null +++ b/src/main/kotlin/io/jmix/cli/env/AgentToolkitMetadata.kt @@ -0,0 +1,124 @@ +package io.jmix.cli.env + +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParseException +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import io.jmix.cli.util.Http +import io.jmix.cli.util.describeIoError +import io.jmix.cli.util.hostOf +import io.jmix.cli.util.string +import java.io.FileNotFoundException +import java.io.IOException +import java.time.Duration +import kotlin.text.Charsets.UTF_8 + +/** + * A server or an agent the toolkit offers. For an agent, [projectConfig] is the project MCP config file the + * toolkit writes for it, relative to the project root (null when the toolkit names none), and [skipServers] + * are the servers the toolkit never configures for it. + */ +data class ToolkitChoice( + val value: String, + val label: String, + val projectConfig: String? = null, + val skipServers: List = emptyList(), +) + +/** The MCP servers and AI agents the CLI offers, in the toolkit's order. */ +data class ToolkitMcpOptions(val servers: List, val agents: List) + +/** + * Reads the files the Jmix Agent Toolkit publishes for its consumers (Jmix Studio reads the same ones), + * so the CLI keeps no copy of the toolkit's servers and agents. + */ +object AgentToolkitMetadata { + + /** + * Text of [path] on toolkit ref [ref] (a branch or HEAD). Throws FileNotFoundException for HTTP 404, + * and another IOException when the file is larger than 256 KiB or unreachable; every message names the file. + */ + fun fetch(ref: String, path: String, timeout: Duration): String = + fetch(ref, path, timeout, AgentToolkitInstaller.RAW_CONTENT_BASE) + + internal fun fetch(ref: String, path: String, timeout: Duration, base: String): String { + val failure = "Cannot load $path from Agent Toolkit $ref" + val response = try { + // Http.send bounds the whole exchange by the request timeout. + Http.sendBytes(Http.client, Http.request("$base/$ref/$path", timeout).GET().build(), MAX_FILE_BYTES) + } catch (e: IOException) { + throw IOException("$failure: ${describeIoError(e, hostOf(base))}", e) + } + val status = response.statusCode() + if (status != 200) { + throw if (status == 404) FileNotFoundException("$failure: HTTP $status") else IOException("$failure: HTTP $status") + } + return String(response.body(), UTF_8) + } + + /** Loads `.studio/studio-meta-data.json` of [ref] and applies [parseMcpOptions]. */ + fun mcpOptions(ref: String, timeout: Duration = Duration.ofSeconds(15)): ToolkitMcpOptions = + mcpOptions(ref, timeout, AgentToolkitInstaller.RAW_CONTENT_BASE) + + internal fun mcpOptions(ref: String, timeout: Duration, base: String): ToolkitMcpOptions = + parseMcpOptions(fetch(ref, METADATA_PATH, timeout, base)) + + /** + * The choices the toolkit enables by default, without the servers its step asks a text input for: + * the installer prompts for that text, and the CLI never lets it prompt. + */ + internal fun parseMcpOptions(json: String): ToolkitMcpOptions { + val root = try { + JsonParser.parseString(json) as? JsonObject + } catch (e: JsonParseException) { + throw unexpectedFormat() + } + val steps = objects((root?.get("install-flow") as? JsonObject)?.get("steps")) + val inputs = objects(steps.firstOrNull { it.string("id") == MCP_STEP }?.get("inputs")) + val textInputs = inputs.filter { it.string("type") == TEXT_INPUT_TYPE }.mapNotNull { it.string("id") } + val servers = choices(inputs, SERVERS_INPUT).filterNot { server -> + // Letters and digits alone: an input id has no `-` or `.`, and `_` may be kept or dropped. + val prefix = server.value.filter(Char::isLetterOrDigit) + textInputs.any { it.filter(Char::isLetterOrDigit).startsWith(prefix, ignoreCase = true) } + } + val agents = choices(inputs, AGENTS_INPUT) + if (servers.isEmpty() || agents.isEmpty()) throw unexpectedFormat() + return ToolkitMcpOptions(servers, agents) + } + + private fun choices(inputs: List, inputId: String): List = + objects(inputs.firstOrNull { it.string("id") == inputId }?.get("choices")).mapNotNull { choice -> + val value = choice.string("value")?.takeIf { CHOICE_VALUE.matches(it) } ?: return@mapNotNull null + val isDefault = (choice.get("default") as? JsonPrimitive)?.takeIf { it.isBoolean }?.asBoolean == true + if (!isDefault) return@mapNotNull null + val label = choice.string("label")?.filterNot(Char::isISOControl)?.takeIf { it.isNotBlank() } + // Only compared with server ids, never passed on: any text will do. + val skipServers = (choice.get("skipServers") as? JsonArray) + ?.mapNotNull { (it as? JsonPrimitive)?.takeIf(JsonPrimitive::isString)?.asString }.orEmpty() + ToolkitChoice(value, label ?: value, choice.string("projectConfig")?.takeIf(::isProjectPath), skipServers) + } + + /** A path the toolkit may name inside a project: relative, plain elements, no `.` or `..`. */ + private fun isProjectPath(path: String): Boolean = + PROJECT_PATH.matches(path) && path.split('/').none { it == "." || it == ".." } + + /** [element] as an array of objects; anything else is not the toolkit's format. */ + private fun objects(element: JsonElement?): List = + (element as? JsonArray)?.map { it as? JsonObject ?: throw unexpectedFormat() } ?: throw unexpectedFormat() + + // Gson's own message is dropped: it quotes the document. + private fun unexpectedFormat() = IOException("Unexpected Agent Toolkit metadata format.") + + internal const val METADATA_PATH = ".studio/studio-meta-data.json" + private const val MCP_STEP = "mcp" + private const val SERVERS_INPUT = "mcpServers" + private const val AGENTS_INPUT = "mcpAgents" + private const val TEXT_INPUT_TYPE = "userInput" + private const val MAX_FILE_BYTES = 256 * 1024 + + // Safe as one element of a comma-separated installer argument, and never an option. + private val CHOICE_VALUE = Regex("[A-Za-z0-9][A-Za-z0-9._-]*") + private val PROJECT_PATH = Regex("[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*") +} diff --git a/src/main/kotlin/io/jmix/cli/env/AgentToolkitStatus.kt b/src/main/kotlin/io/jmix/cli/env/AgentToolkitStatus.kt new file mode 100644 index 0000000..ee312c8 --- /dev/null +++ b/src/main/kotlin/io/jmix/cli/env/AgentToolkitStatus.kt @@ -0,0 +1,193 @@ +package io.jmix.cli.env + +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import io.jmix.cli.util.string +import java.io.IOException +import java.io.OutputStream +import java.nio.file.Files +import java.nio.file.LinkOption.NOFOLLOW_LINKS +import java.nio.file.Path +import java.security.DigestOutputStream +import java.security.MessageDigest +import java.time.Duration +import java.util.Arrays +import java.util.HexFormat +import java.util.concurrent.Callable +import java.util.concurrent.Executors +import kotlin.text.Charsets.UTF_8 + +/** + * Compares the skills, the guidelines and the MCP configs of a project with the files the Jmix Agent Toolkit + * publishes for that purpose (Jmix Studio reads the same ones). The skills folder, the skill names, the + * guidelines marker, the servers and the agents' config files come from those files; none are named here. + */ +object AgentToolkitStatus { + enum class State { NOT_INSTALLED, UP_TO_DATE, UPDATE_AVAILABLE } + + /** + * A null state means the toolkit file it needs could not be read or understood. [mcpOptions] are the MCP + * choices of the metadata the MCP state comes from, so the questions that follow need not load it again. + */ + data class Status( + val skills: State?, + val guidelines: State?, + val mcp: State? = null, + val mcpOptions: ToolkitMcpOptions? = null, + ) + + /** [fetch] returns the text of a toolkit file of [ref] by its repository path, or null. */ + fun detect( + projectDir: Path, + ref: String, + fetch: (path: String) -> String? = { AgentToolkitMetadata.fetch(ref, it, FETCH_TIMEOUT) }, + ): Status { + // All at once: each request may take its whole timeout. + val (manifest, block, metadata) = Executors.newVirtualThreadPerTaskExecutor().use { requests -> + listOf(MANIFEST_PATH, BLOCK_PATH, AgentToolkitMetadata.METADATA_PATH) + .map { path -> requests.submit(Callable { orNull { fetch(path) } }) } + .map { it.get() } + } + val mcpOptions = orNull { metadata?.let(AgentToolkitMetadata::parseMcpOptions) } + return Status( + orNull { skills(projectDir, manifest) }, + orNull { guidelines(projectDir, block) }, + orNull { mcpOptions?.let { mcp(projectDir, it) } }, + mcpOptions, + ) + } + + /** + * Byte-identical to the toolkit's `.studio/gen_skills_manifest.py`: every regular file below a listed skill + * directory is its path relative to [skillsDir] with `/` separators as UTF-8, a zero byte and the file's + * bytes; the entries are hashed in the order of their path bytes, compared as unsigned values. The toolkit + * installs no links, so a link, or a file a Windows junction leads to outside [skillsDir], is left out + * unread: the CLI never reads a file outside the folder, and the hash then differs where one replaced a + * toolkit file. + */ + internal fun skillsHash(skillsDir: Path, skillNames: List): String { + val store = skillsDir.toRealPath() + val files = skillNames.map(skillsDir::resolve).filter { Files.isDirectory(it) }.flatMap { skill -> + Files.walk(skill).use { paths -> + paths.filter { Files.isRegularFile(it, NOFOLLOW_LINKS) && it.toRealPath().startsWith(store) } + .map { skillsDir.relativize(it).joinToString("/").toByteArray(UTF_8) to it } + .toList() + } + } + val digest = MessageDigest.getInstance("SHA-256") + for ((path, file) in files.sortedWith { a, b -> Arrays.compareUnsigned(a.first, b.first) }) { + digest.update(path) + digest.update(0) + Files.newInputStream(file).use { it.transferTo(DigestOutputStream(OutputStream.nullOutputStream(), digest)) } + } + return HexFormat.of().formatHex(digest.digest()) + } + + private fun skills(projectDir: Path, manifest: String?): State? { + val root = manifest?.let { JsonParser.parseString(it) as? JsonObject } ?: return null + val sha256 = root.string("sha256") ?: return null + val listed = root.get("skills") as? JsonArray ?: return null + val local = (root.get("store") as? JsonObject)?.string("local") ?: return null + val store = inProject(projectDir, local) ?: return null + // The manifest is external input: a name is followed only when it is one plain path element. + val names = listed.mapNotNull { (it as? JsonPrimitive)?.takeIf(JsonPrimitive::isString)?.asString } + .filter(SKILL_NAME::matches) + return when { + names.none { Files.isDirectory(store.resolve(it)) } -> State.NOT_INSTALLED + skillsHash(store, names) == sha256 -> State.UP_TO_DATE + else -> State.UPDATE_AVAILABLE + } + } + + /** + * The project configs are the ones the toolkit names for its default agents. Up to date when one of them + * names every offered server the toolkit configures for its agent; only the names are compared. Not + * installed when none of them exists or names an offered server. + */ + private fun mcp(projectDir: Path, options: ToolkitMcpOptions): State? { + val servers = options.servers.map { it.value } + val configs = options.agents.mapNotNull { agent -> + val file = agent.projectConfig?.let { inProject(projectDir, it) } ?: return@mapNotNull null + file to servers - agent.skipServers.toSet() + } + if (configs.isEmpty()) return null + // The offered servers each existing config names; null for one that cannot be read. + val found = configs.filter { (file, _) -> Files.isRegularFile(file) } + .map { (file, expected) -> expected to readOrNull(file)?.let { namedServers(it, servers) } } + return when { + found.any { (expected, named) -> expected.isNotEmpty() && named?.containsAll(expected) == true } -> State.UP_TO_DATE + found.any { (_, named) -> !named.isNullOrEmpty() } -> State.UPDATE_AVAILABLE + found.any { (_, named) -> named == null } -> null + else -> State.NOT_INSTALLED + } + } + + /** + * The [servers] that [text] names as a JSON key (`"id":`) or as the last key of a TOML table header + * (`[mcp_servers.id]`). Headers are read as the installers read them: spaces, quotes and a BOM do not count. + */ + private fun namedServers(text: String, servers: List): Set { + val tables = text.lineSequence() + .map { it.trimStart(' ', '\t', BOM.single()) } + .filter { it.startsWith("[") } + .map { line -> line.trimStart('[').substringBefore(']').filterNot { it in TOML_IGNORED } } + .toSet() + return servers.filterTo(mutableSetOf()) { id -> + tables.any { it == id || it.endsWith(".$id") } || Regex("\"${Regex.escape(id)}\"\\s*:").containsMatchIn(text) + } + } + + /** The text of [file]; null when it is too large or cannot be read. Bytes that are not UTF-8 are replaced. */ + private fun readOrNull(file: Path): String? = try { + if (Files.size(file) > MAX_FILE_BYTES) null else String(Files.readAllBytes(file), UTF_8) + } catch (e: IOException) { + null + } + + /** + * [relative] inside the project, or null when it leads out of it or is the project itself. A link can lead + * out of the project too; nothing out there is read. + */ + private fun inProject(projectDir: Path, relative: String): Path? { + val project = projectDir.toAbsolutePath().normalize() + val path = project.resolve(relative).normalize() + if (Path.of(relative).isAbsolute || path == project || !path.startsWith(project)) return null + if (Files.exists(path) && !path.toRealPath().startsWith(project.toRealPath())) return null + return path + } + + private fun guidelines(projectDir: Path, block: String?): State? { + val expected = block?.let(::unixText)?.trim()?.takeIf { it.isNotEmpty() } ?: return null + val file = inProject(projectDir, GUIDELINES_FILE) ?: return null + if (!Files.isRegularFile(file)) return State.NOT_INSTALLED + // The installers keep the user's bytes around the block: text that is not UTF-8 still holds it. + val text = readOrNull(file)?.let(::unixText) ?: return null + return when { + expected in text -> State.UP_TO_DATE + // The first line of the block is the toolkit's marker of its own section. + expected.lineSequence().first() in text.lineSequence() -> State.UPDATE_AVAILABLE + else -> State.NOT_INSTALLED + } + } + + private fun unixText(text: String) = text.removePrefix(BOM).replace("\r\n", "\n") + + /** A hint is an extra: whatever prevents one leaves it out. */ + private fun orNull(block: () -> T?): T? = try { + block() + } catch (e: Exception) { + if (e is InterruptedException) Thread.currentThread().interrupt() + null + } + + private const val MANIFEST_PATH = ".studio/skills-manifest.json" + private const val BLOCK_PATH = "content/guidelines-block.md" + private const val GUIDELINES_FILE = "AGENTS.md" + private const val BOM = "\uFEFF" + private const val TOML_IGNORED = " \t\"'" + private const val MAX_FILE_BYTES = 4L * 1024 * 1024 + private val FETCH_TIMEOUT: Duration = Duration.ofSeconds(3) + private val SKILL_NAME = Regex("[A-Za-z0-9][A-Za-z0-9._-]*") +} diff --git a/src/main/kotlin/io/jmix/cli/env/ProjectLauncher.kt b/src/main/kotlin/io/jmix/cli/env/ProjectLauncher.kt index ca5fc66..ce30edc 100644 --- a/src/main/kotlin/io/jmix/cli/env/ProjectLauncher.kt +++ b/src/main/kotlin/io/jmix/cli/env/ProjectLauncher.kt @@ -121,11 +121,14 @@ object ProjectLauncher { } ?: DEFAULT_SERVER_PORT } - /** Metadata is optional, including in downloaded projects with unusually large build files. */ + /** + * Metadata is optional, including in downloaded projects with unusually large build files. + * Only a regular file is opened: a pipe or a device at that path would block the read. + */ internal fun readProjectMetadata(file: Path): String? = try { val limit = 1024 * 1024 - Files.newInputStream(file).use { it.readNBytes(limit + 1) } - .takeIf { it.size <= limit }?.decodeToString() + file.takeIf { Files.isRegularFile(it) }?.let { Files.newInputStream(it).use { input -> input.readNBytes(limit + 1) } } + ?.takeIf { it.size <= limit }?.decodeToString() } catch (e: IOException) { null } diff --git a/src/main/kotlin/io/jmix/cli/trial/TrialArchive.kt b/src/main/kotlin/io/jmix/cli/trial/TrialArchive.kt index b25179a..0fcb4c8 100644 --- a/src/main/kotlin/io/jmix/cli/trial/TrialArchive.kt +++ b/src/main/kotlin/io/jmix/cli/trial/TrialArchive.kt @@ -11,6 +11,7 @@ import io.jmix.cli.util.isSecureOrLoopback import io.jmix.cli.util.isZip import java.io.IOException import java.io.InputStream +import java.io.UncheckedIOException import java.net.URI import java.net.http.HttpResponse import java.net.http.HttpTimeoutException @@ -149,19 +150,25 @@ internal object TrialArchive { /** * The Jmix version of [projectDir]: the first `bomVersion` in its root build file, then in the build files of - * the builds under `demo/` by name. A `.trial` suffix is dropped. Null when there is none or it does not look - * like a version. Trials run on the newest Jmix, so only the shape is checked: the template-version filter - * would reject it. + * the builds under `demo/` by name. Only when no file has a literal one, the first `io.jmix` plugin version over + * the same files: generated projects set `bomVersion = version`. A `.trial` suffix is dropped, and a value + * that does not look like a version, such as an interpolated one, is skipped. Null when nothing is left. + * Trials run on the newest Jmix, so only the shape is checked: the template-version filter would reject it. */ fun jmixVersion(projectDir: Path): String? { - val bomVersion = (listOf(projectDir) + demoDirs(projectDir)) - .flatMap { dir -> BUILD_FILES.map(dir::resolve) } - .firstNotNullOfOrNull { file -> - ProjectLauncher.readProjectMetadata(file)?.let { BOM_VERSION.find(it)?.groupValues?.get(1) } - } - return bomVersion?.removeSuffix(".trial")?.takeIf { TemplateRepository.VERSION_SHAPE.matches(it) } + // One pass, one file in memory at a time: a bomVersion returns at once, a plugin version waits for the end. + var pluginVersion: String? = null + for (file in (listOf(projectDir) + demoDirs(projectDir)).flatMap { dir -> BUILD_FILES.map(dir::resolve) }) { + val text = ProjectLauncher.readProjectMetadata(file) ?: continue + usableVersion(BOM_VERSION, text)?.let { return it } + if (pluginVersion == null) pluginVersion = usableVersion(PLUGIN_VERSION, text) + } + return pluginVersion } + private fun usableVersion(pattern: Regex, text: String): String? = + pattern.findAll(text).map { it.groupValues[1].removeSuffix(".trial") }.firstOrNull(TemplateRepository.VERSION_SHAPE::matches) + /** The builds under `demo/` that have a Gradle wrapper, by name; [projectDir] itself when there are none. */ fun runnableApps(projectDir: Path): List = demoDirs(projectDir).filter { Files.isRegularFile(it.resolve("gradlew")) }.ifEmpty { listOf(projectDir) } @@ -225,13 +232,21 @@ internal object TrialArchive { private fun demoDirs(projectDir: Path): List { val demo = projectDir.resolve("demo") if (!Files.isDirectory(demo)) return emptyList() - return Files.list(demo).use { entries -> entries.filter { Files.isDirectory(it) }.toList() } - .sortedBy { it.fileName.toString() } + val dirs = try { + Files.list(demo).use { entries -> entries.filter { Files.isDirectory(it) }.toList() } + } catch (e: UncheckedIOException) { + // A folder that fails while it is listed fails like one that cannot be opened. + throw e.cause ?: e + } + return dirs.sortedBy { it.fileName.toString() } } private val BUILD_FILES = listOf("build.gradle", "build.gradle.kts") private val SETTINGS_FILES = listOf("settings.gradle", "settings.gradle.kts") private val BOM_VERSION = Regex("""bomVersion\s*=\s*['"]([^'"]+)['"]""") + // One whitespace run per gap: two optional runs in a row backtrack quadratically on a long run of spaces. + private val PLUGIN_VERSION = + Regex("""\bid\s*(?:\(\s*)?['"]io\.jmix['"]\s*(?:\)\s*)?version\s*(?:\(\s*)?['"]([^'"]+)['"]""") private val EXECUTE_BITS = setOf(OWNER_EXECUTE, GROUP_EXECUTE, OTHERS_EXECUTE) private val REDIRECT_STATUS_CODES = setOf(301, 302, 303, 307, 308) private const val MAX_REDIRECTS = 5 diff --git a/src/main/kotlin/io/jmix/cli/wizard/Prompts.kt b/src/main/kotlin/io/jmix/cli/wizard/Prompts.kt index b06c056..be2c7c6 100644 --- a/src/main/kotlin/io/jmix/cli/wizard/Prompts.kt +++ b/src/main/kotlin/io/jmix/cli/wizard/Prompts.kt @@ -198,6 +198,8 @@ class Prompts( private val compactHeader: (Int) -> List = { emptyList() }, private val headerAnimationDuration: Duration = Duration.ZERO, private val exitOnEof: Boolean = false, + /** With [exitOnEof]: the end of piped input fails with this message instead of quitting with exit code 0. */ + private val eofError: String? = null, // Trailing position keeps `Prompts(terminal) { state }` working. private val wizardUiState: () -> WizardUiState = { WizardUiState() }, ) { @@ -482,6 +484,7 @@ class Prompts( val line = readlnOrNull() if (line == null) { + endInputIfRequested() isInputExhausted = true terminal.println() terminal.println(gray("No more input — using defaults for the remaining steps.")) @@ -987,7 +990,7 @@ class Prompts( if (line == null) { // Ctrl+D on a real terminal is a deliberate abort, like Ctrl+C. if (terminal.terminalInfo.inputInteractive) abort() - if (exitOnEof) quit() + endInputIfRequested() // EOF on piped stdin. Fall back to defaults for this and all // remaining prompts instead of aborting a half-finished wizard. isInputExhausted = true @@ -1147,6 +1150,21 @@ class Prompts( private fun abort(): Nothing = throw CliktError("Aborted.") + /** + * With [exitOnEof], Ctrl+D on a real terminal aborts, and the end of piped input quits, or fails with + * [eofError] when there is one. + */ + private fun endInputIfRequested() { + if (!exitOnEof) return + if (terminal.terminalInfo.inputInteractive) abort() + eofError?.let { + // The prompt or key bar above ends without a line break; the error starts on its own line. + terminal.println() + throw CliktError(it) + } + quit() + } + private fun quit(): Nothing = throw ProgramResult(0) private companion object { diff --git a/src/test/kotlin/io/jmix/cli/MainTest.kt b/src/test/kotlin/io/jmix/cli/MainTest.kt new file mode 100644 index 0000000..747cf32 --- /dev/null +++ b/src/test/kotlin/io/jmix/cli/MainTest.kt @@ -0,0 +1,54 @@ +package io.jmix.cli + +import com.github.ajalt.clikt.core.subcommands +import com.github.ajalt.clikt.testing.test +import io.jmix.cli.account.Session +import io.jmix.cli.account.SessionStore +import io.jmix.cli.command.JmixCli +import io.jmix.cli.telemetry.UsageStatistics +import java.io.ByteArrayInputStream +import java.nio.file.Path +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir + +class MainTest { + + @Test + fun `the command menu lists the commands in their order`(@TempDir dir: Path) { + val names = rootCommand(UsageStatistics(file = dir.resolve("installation-id"))) + .registeredSubcommands().map { it.commandName } + assertEquals(listOf("new", "trial", "agent-toolkit", "login", "logout", "update"), names) + } + + @Test + fun `every command menu row fits an 80-column terminal`(@TempDir dir: Path) { + val commands = rootCommand(UsageStatistics(file = dir.resolve("installation-id"))).registeredSubcommands() + val sessions = SessionStore(dir.resolve("session.json")) + val shown = mutableSetOf() + // The numbered menu, the wider one; signed out it offers login, signed in logout. + for (signedIn in listOf(false, true)) { + if (signedIn) sessions.save(Session("global", "https://sso.invalid", "https://store.invalid", "fixture")) + val rows = menu(JmixCli(sessions).subcommands(commands)).lines() + for (command in commands) { + val help = " — " + command.help(command.resetContext()) + val row = rows.firstOrNull { it.contains(") ${command.commandName} ") } ?: continue + // The captured output never wraps, so the length is what catches a row that does not fit. + assertTrue(row.endsWith(help) && row.length < 80, "${row.length} columns: $row") + shown += command.commandName + } + } + assertEquals(commands.map { it.commandName }.toSet(), shown) + } + + private fun menu(root: JmixCli): String { + val original = System.`in` + System.setIn(ByteArrayInputStream("q\n".toByteArray())) + try { + return root.test("", width = 80).stdout + } finally { + System.setIn(original) + } + } +} diff --git a/src/test/kotlin/io/jmix/cli/command/ToolkitCommandTest.kt b/src/test/kotlin/io/jmix/cli/command/ToolkitCommandTest.kt new file mode 100644 index 0000000..e375ae5 --- /dev/null +++ b/src/test/kotlin/io/jmix/cli/command/ToolkitCommandTest.kt @@ -0,0 +1,842 @@ +package io.jmix.cli.command + +import com.github.ajalt.clikt.testing.test +import com.github.ajalt.mordant.input.KeyboardEvent +import com.github.ajalt.mordant.rendering.AnsiLevel +import com.github.ajalt.mordant.rendering.TextColors.brightRed +import io.jmix.cli.env.AgentToolkitStatus +import io.jmix.cli.env.ToolkitChange +import io.jmix.cli.env.ToolkitChoice +import io.jmix.cli.env.ToolkitMcpOptions +import io.jmix.cli.env.ToolkitResult +import io.jmix.cli.env.ToolkitStep +import io.jmix.cli.wizard.ANSI_SEQUENCE +import java.io.ByteArrayInputStream +import java.io.FileNotFoundException +import java.io.IOException +import java.nio.file.FileSystems +import java.nio.file.Files +import java.nio.file.Path +import java.time.Duration +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.assertTimeoutPreemptively +import org.junit.jupiter.api.io.TempDir +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource + +class ToolkitCommandTest { + @TempDir lateinit var dir: Path + + private class Call(val dir: Path, val version: String, val steps: Set, val servers: List?, val agents: List?) + private val calls = mutableListOf() + private val refs = mutableListOf() + private val timeouts = mutableListOf() + private var result = ToolkitResult(emptyList(), emptyList()) + private var failure: IOException? = null + private var metadataFailure: IOException? = null + private var status: AgentToolkitStatus.Status? = null + private var statusFailure: Exception? = null + private var statusCalls = 0 + private val options = ToolkitMcpOptions( + servers = listOf(ToolkitChoice("jetbrains", "JetBrains"), ToolkitChoice("jmix-docs", "Jmix Docs"), ToolkitChoice("playwright", "Playwright")), + agents = listOf(ToolkitChoice("claude", "Claude Code"), ToolkitChoice("codex", "Codex"), ToolkitChoice("opencode", "OpenCode"), ToolkitChoice("junie", "Junie")), + ) + private val serverIds get() = options.servers.map { it.value } + private val agentIds get() = options.agents.map { it.value } + + private fun command(cwd: Path = dir) = ToolkitCommand( + install = { projectDir, version, steps, servers, agents, _ -> + failure?.let { throw it } + calls += Call(projectDir, version, steps, servers, agents) + result + }, + mcpOptions = { ref, timeout -> + refs += ref + timeouts += timeout + metadataFailure?.let { throw it } + options + }, + status = { _, _ -> + statusCalls++ + statusFailure?.let { throw it } + status + }, + currentDir = { cwd }, + homeDir = { home }, + ) + + /** An empty home, so the project list never looks into the real ~/IdeaProjects. */ + private val home: Path get() = dir.resolve("home") + + private fun project(build: String = "plugins { id 'io.jmix' version '3.1.0' }"): Path = + Files.createDirectories(dir.resolve("demo")).also { Files.writeString(it.resolve("build.gradle"), build) } + + private fun jmixProject(parent: Path, name: String, version: String = "3.1.0"): Path = + Files.createDirectories(parent.resolve(name)).also { + Files.writeString(it.resolve("build.gradle"), "plugins { id 'io.jmix' version '$version' }") + } + + private fun run(vararg args: String) = command().test(args.toList() + "--non-interactive") + + private fun flat(text: String) = text.replace(Regex("\\s+"), " ") + + private fun withStdin(input: String, block: () -> T): T { + val original = System.`in` + System.setIn(ByteArrayInputStream(input.toByteArray())) + try { + return block() + } finally { + System.setIn(original) + } + } + + private fun lines(input: String, vararg args: String, cwd: Path = dir) = withStdin(input) { + command(cwd).test(args.toList(), inputInteractive = false, outputInteractive = false) + } + + /** A raw terminal; a question that runs out of [keys] would wait forever, hence the timeout. */ + private fun raw(vararg args: String, keys: List, cwd: Path = dir) = assertTimeoutPreemptively(Duration.ofSeconds(10)) { + command(cwd).test( + args.toList(), ansiLevel = AnsiLevel.TRUECOLOR, width = 100, height = 30, inputEvents = keys.map { KeyboardEvent(it) }, + ) + } + + @Test + fun `without steps a scripted run sets up everything the toolkit offers`() { + val project = project() + val run = run("--path", project.toString()) + assertEquals(0, run.statusCode, run.stderr) + val call = calls.single() + assertEquals(project, call.dir) + assertEquals("3.1.0", call.version) + assertEquals(ToolkitStep.entries.toSet(), call.steps) + assertEquals(serverIds, call.servers) + assertEquals(agentIds, call.agents) + assertEquals(listOf("v3"), refs) + assertEquals(listOf(Duration.ofSeconds(15)), timeouts) + assertTrue(run.stdout.contains("Project: $project (Jmix 3.1.0, toolkit v3)")) + } + + @ParameterizedTest + @CsvSource( + "skills,SKILLS", "guidelines,GUIDELINES", "mcp,MCP", "mcp skills,SKILLS|MCP", + "guidelines guidelines,GUIDELINES", "skills guidelines mcp,SKILLS|GUIDELINES|MCP", + ) + fun `the named steps run once each and metadata is loaded only for MCP`(named: String, steps: String) { + run(*named.split(' ').toTypedArray(), "--path", project().toString()) + val expected = steps.split('|').map(ToolkitStep::valueOf).toSet() + assertEquals(expected, calls.single().steps) + val mcp = ToolkitStep.MCP in expected + assertEquals(if (mcp) listOf("v3") else emptyList(), refs) + assertEquals(if (mcp) serverIds else null, calls.single().servers) + assertEquals(if (mcp) agentIds else null, calls.single().agents) + } + + @Test + fun `mcp passes the selected servers and agents in toolkit order`() { + run("mcp", "--servers", "playwright, JetBrains", "--agents", "junie,claude", "--path", project().toString()) + assertEquals(listOf("jetbrains", "playwright"), calls.single().servers) + assertEquals(listOf("claude", "junie"), calls.single().agents) + } + + @Test + fun `unknown servers and agents are rejected with the offered values`() { + val servers = run("mcp", "--servers", "context7", "--path", project().toString()) + assertTrue(flat(servers.stderr).contains("Unknown MCP server: context7. Valid values: jetbrains, jmix-docs, playwright.")) + val agents = run("--agents", "cline", "--path", project().toString()) + assertTrue(flat(agents.stderr).contains("Unknown AI agent: cline. Valid values: claude, codex, opencode, junie.")) + val empty = run("mcp", "--servers", ",", "--path", project().toString()) + assertTrue(empty.stderr.contains("Select at least one MCP server.")) + assertEquals(listOf(1, 1, 1), listOf(servers, agents, empty).map { it.statusCode }) + assertTrue(calls.isEmpty()) + } + + @Test + fun `servers and agents apply only to the mcp step`() { + val run = run("skills", "guidelines", "--servers", "jmix-docs", "--path", project().toString()) + assertEquals(1, run.statusCode) + assertEquals("--servers and --agents apply only to the mcp step.", flat(run.stderr).trim()) + assertTrue(calls.isEmpty()) + assertTrue(refs.isEmpty()) + } + + @Test + fun `a usage error does not load the toolkit metadata`() { + val unknownOption = command(cwd = project()).test(listOf("--bogus")) + val unknownAction = command(cwd = project()).test(listOf("everything", "--non-interactive")) + assertEquals(listOf(1, 1), listOf(unknownOption, unknownAction).map { it.statusCode }) + assertTrue(refs.isEmpty()) + assertTrue(calls.isEmpty()) + } + + @Test + fun `fails outside a Gradle project without running the toolkit`() { + val empty = Files.createDirectories(dir.resolve("empty")) + val run = command(cwd = empty).test(listOf("skills", "--non-interactive")) + assertEquals(1, run.statusCode) + assertTrue(flat(run.stderr).contains("No Gradle project found in $empty. Run `jmix agent-toolkit` from the project root or pass --path.")) + assertTrue(calls.isEmpty()) + } + + @Test + fun `the version option overrides detection and an undetected version fails`() { + run("skills", "--jmix-version", "2.8.3", "--path", project().toString()) + assertEquals("2.8.3", calls.single().version) + val bare = Files.createDirectories(dir.resolve("bare")).also { Files.writeString(it.resolve("settings.gradle"), "") } + val run = run("skills", "--path", bare.toString()) + assertEquals(1, run.statusCode) + assertTrue(flat(run.stderr).contains("Cannot detect the Jmix version in $bare. Pass --jmix-version.")) + assertEquals(1, calls.size) + } + + @Test + fun `prints the changes, the backup and the toolkit's notes`() { + result = ToolkitResult( + changes = listOf( + ToolkitChange("updated", ".agents/skills"), ToolkitChange("backed-up", "AGENTS.md.bak"), + ToolkitChange("updated", "AGENTS.md"), ToolkitChange("created", ".mcp.json"), + ), + notes = listOf("Approve the servers.", "Trust the folder."), + ) + val out = run("--path", project().toString()).stdout + assertTrue(out.contains("✓ Agent Toolkit v3 is set up")) + assertTrue(out.contains(" updated .agents/skills")) + assertTrue(out.contains(" backed-up AGENTS.md.bak")) + assertTrue(out.contains(" created .mcp.json")) + assertTrue(out.contains("Notes from the Agent Toolkit:")) + assertTrue(out.indexOf(" • Approve the servers.") in 0 until out.indexOf(" • Trust the folder.")) + } + + @Test + fun `an action this version does not know is still listed`() { + result = ToolkitResult(listOf(ToolkitChange("created", "a.txt"), ToolkitChange("moved-aside", "b.txt")), emptyList()) + val out = run("skills", "--path", project().toString()).stdout + assertTrue(out.contains(" created a.txt")) + assertTrue(out.contains(" moved-aside b.txt")) + } + + @Test + fun `an unchanged project is reported as up to date`() { + val quiet = run("--path", project().toString()).stdout + assertTrue(quiet.contains("✓ Agent Toolkit v3 is already up to date")) + assertFalse(quiet.contains("Notes from the Agent Toolkit:")) + result = ToolkitResult(emptyList(), listOf("Approve the servers.")) + val noted = run("--path", project().toString()).stdout + assertTrue(noted.contains("✓ Agent Toolkit v3 is already up to date")) + assertTrue(noted.contains(" • Approve the servers.")) + } + + @Test + fun `the headline of a run of some steps names those steps only`() { + val quiet = run("mcp", "guidelines", "--path", project().toString()).stdout + assertTrue(quiet.contains("✓ Agent Toolkit v3: guidelines, mcp already up to date"), quiet) + assertFalse(quiet.contains("Agent Toolkit v3 is"), quiet) + result = ToolkitResult(listOf(ToolkitChange("updated", "AGENTS.md")), emptyList()) + val changed = run("guidelines", "--path", project().toString()).stdout + assertTrue(changed.contains("✓ Agent Toolkit v3: guidelines set up"), changed) + } + + @Test + fun `a terminal breaks a long note at spaces under its bullet, piped output keeps it whole`() { + val note = "Codex reads .codex/config.toml only in trusted projects: accept its 'trust this folder' prompt." + result = ToolkitResult(emptyList(), listOf(note)) + val project = project().toString() + val piped = run("mcp", "--path", project).stdout + assertTrue(piped.contains(" • $note"), piped) + val shown = command().test(listOf("mcp", "--non-interactive", "--path", project), width = 40, outputInteractive = true).stdout + val noteLines = shown.lines().dropWhile { !it.startsWith(" • ") }.takeWhile { it.isNotBlank() } + assertTrue(noteLines.size > 1, shown) + assertTrue(noteLines.drop(1).all { it.startsWith(" ") && !it.startsWith(" ") }, shown) + assertTrue(noteLines.all { it.length <= 39 }, shown) + assertEquals(note, noteLines.joinToString(" ") { it.trim().removePrefix("• ") }) + // A terminal that reports no size, such as a PTY opened without one, keeps the note whole. + val sizeless = command().test(listOf("mcp", "--non-interactive", "--path", project), width = 0, outputInteractive = true).stdout + assertTrue(sizeless.contains(" • $note"), sizeless) + } + + @Test + fun `wrapping keeps words whole`() { + assertEquals(listOf("one two", "three", "averyveryverylongword", "x"), wrapWords("one two three averyveryverylongword x", 7)) + assertEquals(emptyList(), wrapWords("", 10)) + } + + @Test + fun `installer and metadata failures stay one concise line`() { + failure = IOException("Agent Toolkit skills step failed: boom") + val failed = run("skills", "--path", project().toString()) + assertEquals(1, failed.statusCode) + assertEquals("Agent Toolkit setup failed: Agent Toolkit skills step failed: boom", failed.stderr.trim()) + failure = null + metadataFailure = IOException("Unexpected Agent Toolkit metadata format.") + val broken = run("mcp", "--path", project().toString()) + assertEquals(1, broken.statusCode) + assertEquals("Agent Toolkit setup failed: Unexpected Agent Toolkit metadata format.", broken.stderr.trim()) + assertTrue(calls.isEmpty()) + } + + @ParameterizedTest + @ValueSource(strings = ["skills mcp", "mcp"]) + fun `a Jmix major without a toolkit branch is named when its metadata is missing`(steps: String) { + metadataFailure = FileNotFoundException("Cannot load .studio/studio-meta-data.json from Agent Toolkit v4: HTTP 404") + val run = run(*steps.split(' ').toTypedArray(), "--jmix-version", "4.0.0", "--path", project().toString()) + assertEquals(1, run.statusCode) + assertEquals("Agent Toolkit setup failed: the toolkit has no v4 branch for Jmix 4 yet", run.stderr.trim()) + // The metadata is loaded while the run is resolved, before the project line. + assertFalse(run.stdout.contains("Project:")) + assertTrue(calls.isEmpty()) + } + + @ParameterizedTest + @ValueSource(strings = ["skills", "guidelines"]) + fun `a step fails below the project line`(step: String) { + failure = IOException("no script") + val project = project() + val run = run(step, "--jmix-version", "4.0.0", "--path", project.toString()) + assertEquals(1, run.statusCode) + assertTrue(run.stdout.contains("✓ Project: $project (Jmix 4.0.0, toolkit v4)")) + assertTrue(run.output.indexOf("✓ Project:") < run.output.indexOf("Agent Toolkit setup failed:")) + } + + @Test + fun `control characters are removed from the failure line`() { + failure = IOException("Agent Toolkit skills step failed: \u001B[31mboom\u0007\r\nnext") + val failed = run("skills", "--path", project().toString()) + assertEquals("Agent Toolkit setup failed: Agent Toolkit skills step failed: [31mboomnext", failed.stderr.trim()) + } + + @Test + fun `control characters are removed from the version and the directory the messages show`() { + val escape = "\u001B[2J" + val run = run("skills", "--jmix-version", "3.${escape}1", "--path", project().toString()) + assertTrue(run.stdout.contains("(Jmix 3.[2J1, toolkit v3)"), run.stdout) + assertFalse(run.output.contains(escape)) + val malformed = run("skills", "--jmix-version", "x$escape", "--path", project().toString()) + assertEquals("Unexpected Jmix version format: x[2J", malformed.stderr.trim()) + // Windows allows no control character in a folder name. + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val bell = Files.createDirectories(dir.resolve("bare\u0007")).also { Files.writeString(it.resolve("settings.gradle"), "") } + val undetected = run("skills", "--path", bell.toString()) + assertEquals("Cannot detect the Jmix version in ${dir.resolve("bare")}. Pass --jmix-version.", flat(undetected.stderr).trim()) + } + + @Test + fun `a path the platform cannot parse fails like a directory without a project`() { + val runs = listOf(run("skills", "--path", "no\u0000path"), lines("2\n", "--path", "no\u0000path")) + for (run in runs) { + assertEquals(1, run.statusCode) + assertEquals( + "No Gradle project found in nopath. Run `jmix agent-toolkit` from the project root or pass --path.", + flat(run.stderr).trim(), + ) + } + assertTrue(calls.isEmpty()) + } + + @Test + fun `a detected version without a numeric major counts as not detected`() { + val odd = project("jmix { bomVersion = 'abc' }") + val scripted = run("skills", "--path", odd.toString()) + assertEquals(1, scripted.statusCode) + assertEquals("Cannot detect the Jmix version in $odd. Pass --jmix-version.", flat(scripted.stderr).trim()) + assertTrue(calls.isEmpty()) + val asked = lines("3.1.0\n$SKILLS_ONLY", "--path", odd.toString()) + assertTrue(asked.output.contains("Jmix version of the project")) + assertEquals("3.1.0", calls.single().version) + val help = command(cwd = odd).test(listOf("--help")) + assertTrue(flat(help.output).contains("MCP servers in Agent Toolkit: jetbrains, jmix-docs, playwright.")) + assertEquals("HEAD", refs.last()) + } + + @Test + fun `an explicit version without a numeric major fails with the branch error`() { + val project = project().toString() + val runs = listOf( + run("skills", "--jmix-version", "latest", "--path", project), + lines("2\n", "--jmix-version", "latest", "--path", project), + ) + for (run in runs) { + assertEquals(1, run.statusCode) + assertEquals("Unexpected Jmix version format: latest", run.stderr.trim()) + } + assertTrue(calls.isEmpty()) + } + + @Test + fun `a malformed version option fails before the project list`() { + jmixProject(dir, "alpha") + val run = lines("1\n", "--jmix-version", "latest") + assertEquals(1, run.statusCode) + assertEquals("Unexpected Jmix version format: latest", run.stderr.trim()) + assertFalse(run.output.contains("Select project directory"), run.output) + assertTrue(calls.isEmpty()) + } + + @Test + fun `Back to the version question offers the version typed before`() { + val bare = Files.createDirectories(dir.resolve("bare")).also { Files.writeString(it.resolve("settings.gradle"), "") } + // The version, Back from the checklist, Enter keeps the version, then skills. + val run = lines("2.8.3\n<\n\n$SKILLS_ONLY", "--path", bare.toString()) + assertEquals(0, run.statusCode, run.stderr) + assertTrue(run.output.contains("Jmix version of the project (2.8.3)"), run.output) + assertEquals("2.8.3", calls.single().version) + } + + @Test + fun `Back from the agents keeps the servers chosen before`() { + val project = project().toString() + // Line input: playwright, Back from the agents, Enter keeps playwright, Enter keeps every agent. + val line = lines("playwright\n<\n\n\n", "mcp", "--path", project) + assertEquals(0, line.statusCode, line.stderr) + assertTrue(line.output.contains("MCP servers (playwright)"), line.output) + // Raw: jmix-docs off, Esc from the agents, the servers keep it off, then Enter twice. + raw("mcp", "--path", project, keys = listOf("ArrowDown", " ", "Enter", "Escape", "Enter", "Enter")) + // Through the steps checklist and forward again: mcp alone, playwright, Back twice, then Enter thrice. + lines("1,2\n\nplaywright\n<\n<\n\n\n\n", "--path", project) + assertEquals(listOf(listOf("playwright"), listOf("jetbrains", "playwright"), listOf("playwright")), calls.map { it.servers }) + assertEquals(listOf(agentIds, agentIds, agentIds), calls.map { it.agents }) + } + + @Test + fun `typed ids match without case`() { + val project = project().toString() + run("mcp", "--servers", "JMIX-DOCS", "--agents", "Claude", "--path", project) + lines("PLAYWRIGHT\nJunie\n", "mcp", "--path", project) + assertEquals(listOf(listOf("jmix-docs") to listOf("claude"), listOf("playwright") to listOf("junie")), calls.map { it.servers to it.agents }) + } + + @Test + fun `help lists what the toolkit offers for the current project`() { + val help = command(cwd = project()).test(listOf("--help")) + assertEquals(0, help.statusCode) + assertTrue(flat(help.output).contains("MCP servers in Agent Toolkit v3: jetbrains, jmix-docs, playwright. AI agents: claude, codex, opencode, junie.")) + assertTrue(flat(help.output).contains("Steps to run: skills, guidelines, mcp")) + assertEquals(listOf("v3"), refs.distinct()) + val outside = command(cwd = Files.createDirectories(dir.resolve("empty"))).test(listOf("--help")) + assertTrue(flat(outside.output).contains("MCP servers in Agent Toolkit: jetbrains, jmix-docs, playwright. AI agents: claude, codex, opencode, junie.")) + assertEquals("HEAD", refs.last()) + assertEquals(listOf(Duration.ofSeconds(3)), timeouts.distinct()) + assertTrue(calls.isEmpty()) + } + + @Test + fun `help survives an unreachable toolkit`() { + metadataFailure = IOException("offline") + val help = command(cwd = project()).test(listOf("--help")) + assertEquals(0, help.statusCode) + assertTrue(flat(help.output).contains("Usage: agent-toolkit")) + assertTrue(flat(help.output).contains("The current MCP servers and AI agents are listed when the Agent Toolkit is reachable.")) + } + + @Test + fun `numbered checklist runs the checked steps and Enter keeps the preselected ones`() { + val project = project().toString() + val skills = lines(SKILLS_ONLY, "--path", project) + assertEquals(0, skills.statusCode, skills.stderr) + assertTrue(skills.output.contains("✓ Steps: skills")) + // Every state is unknown here, so every step starts checked; MCP then asks for its two lists. + lines("\n\n\n", "--path", project) + assertEquals(listOf(setOf(ToolkitStep.SKILLS), ToolkitStep.entries.toSet()), calls.map { it.steps }) + assertEquals(agentIds, calls.last().agents) + } + + @Test + fun `line input reads the MCP lists in option syntax and repeats an invalid one`() { + val run = lines("1,2\n\ncontext7\nplaywright,jmix-docs\n\n", "--path", project().toString()) + assertTrue(run.output.contains("MCP servers (jetbrains,jmix-docs,playwright)")) + assertTrue(flat(run.output).contains("Unknown MCP server: context7. Valid values: jetbrains, jmix-docs, playwright.")) + assertEquals(listOf("jmix-docs", "playwright"), calls.single().servers) + assertEquals(agentIds, calls.single().agents) + } + + @Test + fun `options hide the questions they answer`() { + lines("jmix-docs\n", "mcp", "--agents", "claude", "--path", project().toString()) + assertEquals(listOf("jmix-docs") to listOf("claude"), calls.single().let { it.servers to it.agents }) + } + + @Test + fun `raw mcp flow shows the toolkit's labels and toggles an agent off`() { + val run = raw("mcp", "--path", project().toString(), keys = listOf("Enter", "ArrowDown", " ", "Enter", "q")) + assertTrue(run.output.contains("Jmix Docs")) + assertTrue(run.output.contains("Claude Code")) + assertEquals(serverIds, calls.single().servers) + assertEquals(listOf("claude", "opencode", "junie"), calls.single().agents) + } + + @Test + fun `back leaves the MCP questions and then the command`() { + // mcp alone, Back from the servers; the checklist keeps mcp checked, so skills on and mcp off. + lines("1,2\n\n<\n1,3\n\n", "--path", project().toString()) + assertEquals(setOf(ToolkitStep.SKILLS), calls.single().steps) + assertThrows { lines("<\n", "--path", project().toString()) } + assertEquals(1, calls.size) + } + + @Test + fun `q quits and the end of input fails, both with nothing run`() { + assertEquals(0, lines("q\n", "--path", project().toString()).statusCode) + val noInput = "No input to answer the questions, so nothing was set up. " + + "Use --non-interactive, or pass the answers as arguments and options." + for (eof in listOf(lines("", "--path", project().toString()), lines("", "skills", cwd = project()))) { + assertEquals(1, eof.statusCode) + assertTrue(flat(eof.stderr).contains(noInput), eof.stderr) + } + assertTrue(calls.isEmpty()) + } + + @Test + fun `the project list offers the current directory, nearby Jmix projects and Other`() { + val work = jmixProject(dir, "work", "2.8.3") + val inner = jmixProject(work, "inner") + jmixProject(work, ".hidden") + Files.createDirectories(work.resolve("plain")).also { Files.writeString(it.resolve("settings.gradle"), "") } + val alpha = jmixProject(home.resolve("IdeaProjects"), "alpha") + val out = flat(lines("q\n", cwd = work).output) + val rows = listOf( + "1) Current directory — $work (Jmix 2.8.3)", "2) alpha — $alpha (Jmix 3.1.0)", "3) inner — $inner (Jmix 3.1.0)", "4) Other...", + ).map(out::indexOf) + assertTrue(rows.all { it >= 0 } && rows == rows.sorted(), out) + assertFalse(out.contains(".hidden")) + assertFalse(out.contains("${work.resolve("plain")}")) + assertTrue(calls.isEmpty()) + } + + @Test + fun `with nothing to list the directory is typed until it is a Gradle project`() { + val project = project() + val empty = Files.createDirectories(dir.resolve("empty")) + val run = lines("\n$empty\n$project\n$SKILLS_ONLY", cwd = empty) + assertTrue(run.output.contains("Path cannot be empty.")) + assertTrue(flat(run.output).contains("No Gradle project found in $empty.")) + assertEquals(project, calls.single().dir) + } + + @Test + fun `Back from a typed directory shows the list again, and Back from the list leaves the command`() { + val work = Files.createDirectories(dir.resolve("work")) + val alpha = jmixProject(work, "alpha") + // Other..., Back to the list, alpha, then skills. + lines("2\n<\n1\n$SKILLS_ONLY", cwd = work) + assertEquals(alpha, calls.single().dir) + assertThrows { lines("<\n", cwd = work) } + assertEquals(1, calls.size) + } + + @Test + fun `the project line follows the project chosen after going back`() { + val work = Files.createDirectories(dir.resolve("work")) + val alpha = jmixProject(work, "alpha") + val beta = jmixProject(work, "beta", "2.8.3") + val run = lines("1\n<\n2\n$SKILLS_ONLY", cwd = work) + assertTrue(flat(run.output).contains("Project: $alpha (Jmix 3.1.0, toolkit v3)")) + assertTrue(flat(run.output).contains("Project: $beta (Jmix 2.8.3, toolkit v2)")) + assertEquals(beta, calls.single().dir) + } + + @Test + fun `going back to the project list keeps the chosen project selected`() { + val work = Files.createDirectories(dir.resolve("work")) + jmixProject(work, "alpha") + val beta = jmixProject(work, "beta") + val typed = project() + // beta, Back from the checklist, Enter keeps beta, then skills; the folders are looked into once. + val run = lines("2\n<\n\n$SKILLS_ONLY", cwd = work) + assertEquals(1, Regex("Looking for Jmix projects").findAll(run.output).count(), run.output) + // A typed directory comes back as the answer prefilled under Other.... + lines("3\n$typed\n<\n\n\n$SKILLS_ONLY", cwd = work) + assertEquals(listOf(beta, typed), calls.map { it.dir }) + } + + @Test + fun `raw project list picks a nearby project and Esc leaves the command`() { + val work = Files.createDirectories(dir.resolve("work")) + jmixProject(work, "alpha") + val beta = jmixProject(work, "beta") + // beta, then guidelines and mcp unchecked. + val run = raw(keys = listOf("ArrowDown", "Enter", "ArrowDown", " ", "ArrowDown", " ", "Enter"), cwd = work) + assertEquals(0, run.statusCode, run.stderr) + assertTrue(run.output.contains("Select project directory")) + assertEquals(beta to setOf(ToolkitStep.SKILLS), calls.single().let { it.dir to it.steps }) + assertThrows { raw(keys = listOf("Escape"), cwd = work) } + assertEquals(1, calls.size) + } + + @Test + fun `an explicit path that is no project fails instead of asking`() { + val empty = Files.createDirectories(dir.resolve("empty")) + val run = lines("2\n", "--path", empty.toString()) + assertEquals(1, run.statusCode) + assertTrue(flat(run.stderr).contains("No Gradle project found in $empty. Run `jmix agent-toolkit` from the project root or pass --path.")) + assertTrue(calls.isEmpty()) + } + + @Test + fun `MCP options keep the MCP step checked`() { + // Toggling all three leaves mcp checked; the agents are still asked. + val run = lines("1,2,3\n\n\n", "--servers", "jmix-docs", "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + assertTrue(flat(run.output).contains("(included) mcp")) + assertEquals(Triple(setOf(ToolkitStep.MCP), listOf("jmix-docs"), agentIds), calls.single().let { Triple(it.steps, it.servers, it.agents) }) + } + + @Test + fun `an undetected version is asked for`() { + val bare = Files.createDirectories(dir.resolve("bare")).also { Files.writeString(it.resolve("settings.gradle"), "") } + val run = lines("latest\n3.1.0\n$SKILLS_ONLY", "--path", bare.toString()) + assertTrue(run.output.contains("Enter a Jmix version such as 3.1.0.")) + assertEquals("3.1.0", calls.single().version) + // The directory is named above the question, before its version is known. + val out = flat(run.output) + assertTrue(out.indexOf("✓ Project: $bare") in 0 until out.indexOf("Jmix version of the project"), out) + } + + @Test + fun `after Back from a typed directory the list keeps Other selected`() { + val work = Files.createDirectories(dir.resolve("work")) + jmixProject(work, "alpha") + val typed = project() + // Other..., Back to the list, Enter keeps Other..., the directory, then skills. + lines("2\n<\n\n$typed\n$SKILLS_ONLY", cwd = work) + assertEquals(typed, calls.single().dir) + } + + @Test + fun `Back from the version question returns to the project list`() { + val work = Files.createDirectories(dir.resolve("work")) + val alpha = jmixProject(work, "alpha") + val bare = Files.createDirectories(dir.resolve("bare")).also { Files.writeString(it.resolve("settings.gradle"), "") } + // Other..., the project without a version, Back from its version question, then alpha and skills. + val run = lines("2\n$bare\n<\n1\n$SKILLS_ONLY", cwd = work) + assertTrue(run.output.contains("Jmix version of the project")) + assertEquals(alpha, calls.single().dir) + } + + @Test + fun `a project below the current directory and in IdeaProjects is listed once`() { + val ideaProjects = home.resolve("IdeaProjects") + jmixProject(ideaProjects, "alpha") + val out = flat(lines("q\n", cwd = ideaProjects).output) + assertEquals(1, Regex("""\d\) alpha —""").findAll(out).count(), out) + } + + @Test + fun `the current directory is not listed again among the projects next to it`() { + val ideaProjects = home.resolve("IdeaProjects") + val demo = jmixProject(ideaProjects, "demo") + jmixProject(ideaProjects, "alpha") + val out = flat(lines("q\n", cwd = demo).output) + assertTrue(out.contains("1) Current directory — $demo (Jmix 3.1.0)"), out) + assertFalse(out.contains("demo — "), out) + assertTrue(out.contains("2) alpha — "), out) + } + + @Test + fun `with Other the only entry Back leaves the command`() { + assertThrows { lines("<\n", cwd = Files.createDirectories(dir.resolve("empty"))) } + assertTrue(calls.isEmpty()) + } + + @Test + fun `started in the home directory the list does not look into its folders`() { + jmixProject(home, "pet") + val alpha = jmixProject(home.resolve("IdeaProjects"), "alpha") + val out = flat(lines("q\n", cwd = home).output) + assertTrue(out.contains("alpha — $alpha"), out) + assertFalse(out.contains("pet —"), out) + } + + @Test + fun `a folder whose name has a control character is not listed`() { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val work = Files.createDirectories(dir.resolve("work")) + jmixProject(work, "bell\u0007") + jmixProject(work, "alpha") + val out = lines("q\n", cwd = work).output + assertTrue(out.contains("alpha")) + assertFalse(out.contains("bell")) + } + + @Test + fun `the checklist shows each state and leaves only the up-to-date steps unchecked`() { + status = AgentToolkitStatus.Status(UPDATE_AVAILABLE, UP_TO_DATE, NOT_INSTALLED) + val out = flat(lines("q\n", "--path", project().toString()).output) + assertTrue(out.contains("[x] 1) skills — Update agent skills · update available"), out) + assertTrue(out.contains("[ ] 2) guidelines — Generate AGENTS.md guidelines · up to date"), out) + assertTrue(out.contains("[x] 3) mcp — Configure MCP servers · not installed"), out) + assertFalse(out.contains("Everything is up to date")) + status = AgentToolkitStatus.Status(NOT_INSTALLED, null, null) + val partial = flat(lines("q\n", "--path", project().toString()).output) + assertTrue(partial.contains("[x] 1) skills — Update agent skills · not installed"), partial) + assertTrue(partial.contains("[x] 2) guidelines — Generate AGENTS.md guidelines [x] 3)"), partial) + status = null + assertFalse(lines("q\n", "--path", project().toString()).output.contains(" · ")) + assertTrue(calls.isEmpty()) + } + + @Test + fun `Enter keeps the preselected steps, which leave out the up-to-date ones`() { + status = AgentToolkitStatus.Status(UP_TO_DATE, UPDATE_AVAILABLE, null) + val run = lines("\n\n\n", "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + assertEquals(setOf(ToolkitStep.GUIDELINES, ToolkitStep.MCP), calls.single().steps) + } + + @Test + fun `the MCP lists are asked when mcp is chosen with other steps`() { + val run = lines("\njmix-docs\nclaude\n", "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + val call = calls.single() + assertEquals(Triple(ToolkitStep.entries.toSet(), listOf("jmix-docs"), listOf("claude")), Triple(call.steps, call.servers, call.agents)) + } + + @Test + fun `the MCP questions use the metadata the status was found with`() { + status = AgentToolkitStatus.Status(null, null, null, options) + lines("1,2\n\n\n\n", "--path", project().toString()) + assertEquals(setOf(ToolkitStep.MCP), calls.single().steps) + assertTrue(refs.isEmpty(), "$refs") + } + + @Test + fun `with MCP options an up-to-date project gets no legend, and mcp runs alone`() { + status = AgentToolkitStatus.Status(UP_TO_DATE, UP_TO_DATE, UP_TO_DATE) + val run = lines("\n\n", "--servers", "jmix-docs", "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + val out = flat(run.output) + assertTrue(out.contains("[x] 3) (included) mcp"), out) + assertFalse(out.contains("Everything is up to date"), out) + assertEquals(setOf(ToolkitStep.MCP), calls.single().steps) + } + + @Test + fun `an empty choice in a raw terminal is reported after the questions`() { + status = AgentToolkitStatus.Status(UP_TO_DATE, UP_TO_DATE, UP_TO_DATE) + val project = project() + val run = raw("--path", project.toString(), keys = listOf("Enter")) + assertEquals(0, run.statusCode, run.stderr) + val afterQuestions = ANSI_SEQUENCE.replace(run.output.substringAfterLast(EXIT_ALTERNATE_SCREEN), "") + val positions = listOf("✓ Project: $project (Jmix 3.1.0, toolkit v3)", "Nothing selected, so nothing was changed.") + .map(afterQuestions::indexOf) + assertTrue(positions.all { it >= 0 } && positions == positions.sorted(), afterQuestions) + assertTrue(calls.isEmpty()) + } + + @Test + fun `with everything up to date nothing is checked, and an empty choice changes nothing`() { + status = AgentToolkitStatus.Status(UP_TO_DATE, UP_TO_DATE, UP_TO_DATE) + val run = lines("\n", "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + val out = flat(run.output) + assertTrue(out.contains("Everything is up to date. Select a step to run it anyway."), out) + assertTrue(out.contains("Nothing selected, so nothing was changed."), out) + assertFalse(out.contains("✓ Steps:"), out) + assertTrue(calls.isEmpty()) + assertTrue(refs.isEmpty()) + // A step can still be run on purpose. + lines("1\n\n", "--path", project().toString()) + assertEquals(setOf(ToolkitStep.SKILLS), calls.single().steps) + } + + @Test + fun `an interactive run that asks nothing stays on the main screen and needs no key`() { + val project = project().toString() + val quiet = listOf( + raw("skills", "--path", project, keys = emptyList()), + raw("mcp", "--servers", "jmix-docs", "--agents", "claude", "--path", project, keys = emptyList()), + ) + for (run in quiet) { + assertEquals(0, run.statusCode, run.stderr) + assertFalse(run.output.contains(ENTER_ALTERNATE_SCREEN)) + } + assertEquals(listOf(setOf(ToolkitStep.SKILLS), setOf(ToolkitStep.MCP)), calls.map { it.steps }) + assertEquals(0, statusCalls) + assertTrue(raw("--path", project, keys = listOf("Enter", "Enter", "Enter")).output.contains(ENTER_ALTERNATE_SCREEN)) + } + + @Test + fun `raw Esc returns to the previous question and from the first one to the command menu`() { + val project = project().toString() + // mcp alone, the servers; Esc from the agents, Esc from the servers; the checklist keeps mcp, so skills instead. + val keys = listOf( + " ", "ArrowDown", " ", "Enter", "Enter", "Escape", "Escape", " ", "ArrowDown", "ArrowDown", " ", "Enter", + ) + assertEquals(0, raw("--path", project, keys = keys).statusCode) + assertEquals(setOf(ToolkitStep.SKILLS), calls.single().steps) + assertEquals(1, statusCalls) + assertThrows { raw("--path", project, keys = listOf("Escape")) } + assertEquals(1, calls.size) + } + + @Test + fun `raw q quits from a list with nothing run`() { + val project = project().toString() + assertEquals(0, raw("--path", project, keys = listOf("q")).statusCode) + assertEquals(0, raw("mcp", "--path", project, keys = listOf("Enter", "q")).statusCode) + assertTrue(calls.isEmpty()) + } + + @Test + fun `a checklist confirmed empty asks again with the reason in red`() { + val keys = listOf(" ", "ArrowDown", " ", "ArrowDown", " ", "Enter", "Enter", "Enter") + val run = raw("mcp", "--path", project().toString(), keys = keys) + assertTrue(run.output.contains(brightRed("Select at least one MCP server."))) + assertEquals(serverIds to agentIds, calls.single().let { it.servers to it.agents }) + } + + @Test + fun `the answers are printed again after the questions of a raw terminal`() { + val project = project() + val keys = listOf(" ", "ArrowDown", " ", "Enter", "Enter", "ArrowDown", " ", "Enter") + val run = raw("--path", project.toString(), keys = keys) + val afterQuestions = ANSI_SEQUENCE.replace(run.output.substringAfterLast(EXIT_ALTERNATE_SCREEN), "") + val positions = listOf( + "✓ Project: $project (Jmix 3.1.0, toolkit v3)", "✓ Steps: mcp", "✓ MCP servers: jetbrains, jmix-docs, playwright", + "✓ AI agents: claude, opencode, junie", "✓ Agent Toolkit v3: mcp already up to date", + ).map(afterQuestions::indexOf) + assertTrue(positions.all { it >= 0 } && positions == positions.sorted(), afterQuestions) + } + + @Test + fun `back to the checklist does not detect the status again`() { + lines("1,2\n\n<\n1,3\n\n", "--path", project().toString()) + assertEquals(setOf(ToolkitStep.SKILLS), calls.single().steps) + assertEquals(1, statusCalls) + } + + @Test + fun `a status check that throws still shows the checklist, without hints`() { + statusFailure = IllegalStateException("boom") + val run = lines(SKILLS_ONLY, "--path", project().toString()) + assertEquals(0, run.statusCode, run.stderr) + assertTrue(run.output.contains("Update agent skills")) + assertFalse(run.output.contains(" · ")) + assertEquals(setOf(ToolkitStep.SKILLS), calls.single().steps) + assertEquals(1, statusCalls) + } + + @Test + fun `scripted runs do not ask for the status`() { + var asked = 0 + ToolkitCommand( + install = { _, _, _, _, _, _ -> result }, mcpOptions = { _, _ -> options }, + status = { _, _ -> asked++; null }, currentDir = { dir }, + ).test(listOf("skills", "--non-interactive", "--path", project().toString())) + assertEquals(0, asked) + } + + private companion object { + /** In the numbered checklist with every step checked: unchecks guidelines and mcp, then confirms. */ + const val SKILLS_ONLY = "2,3\n\n" + val UP_TO_DATE = AgentToolkitStatus.State.UP_TO_DATE + val UPDATE_AVAILABLE = AgentToolkitStatus.State.UPDATE_AVAILABLE + val NOT_INSTALLED = AgentToolkitStatus.State.NOT_INSTALLED + const val ENTER_ALTERNATE_SCREEN = "\u001B[?1049h" + const val EXIT_ALTERNATE_SCREEN = "\u001B[?1049l" + } +} diff --git a/src/test/kotlin/io/jmix/cli/command/TrialCommandTest.kt b/src/test/kotlin/io/jmix/cli/command/TrialCommandTest.kt index 53ee910..4c5d1a3 100644 --- a/src/test/kotlin/io/jmix/cli/command/TrialCommandTest.kt +++ b/src/test/kotlin/io/jmix/cli/command/TrialCommandTest.kt @@ -307,7 +307,7 @@ class TrialCommandTest { @Test fun `trial help lists its options and the update flag`() { val help = TrialCommand().test("--help", width = 200).stdout - assertTrue(help.contains("Download the Enterprise+BPM trial project of your Jmix account"), help) + assertTrue(help.contains("Download the Enterprise+BPM trial of your Jmix account"), help) for (option in listOf("--path", "--start-trial", "--non-interactive", "--no-update")) { assertTrue(help.contains(option), help) } diff --git a/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerIntegrationTest.kt b/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerIntegrationTest.kt index 8ced99b..7244518 100644 --- a/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerIntegrationTest.kt +++ b/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerIntegrationTest.kt @@ -2,12 +2,16 @@ package io.jmix.cli.env import com.google.gson.JsonObject import com.google.gson.JsonParser +import java.io.IOException import java.nio.file.Files import java.nio.file.LinkOption.NOFOLLOW_LINKS import java.nio.file.Path +import java.time.Duration import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest @@ -16,7 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource /** * Downloads the real Agent Toolkit installer and runs its non-interactive * subcommands against a temporary project directory. Everything it writes is - * project-local, so the test never touches global agent directories. + * project-local, so the test never touches global agent directories. The installer's MCP + * step still reads the user's Codex config ($CODEX_HOME or ~/.codex/config.toml): a global + * server with the same name and another transport fails the MCP tests on that machine. * Needs network; enable with JMIX_CLI_IT=true (set in CI). */ @EnabledIfEnvironmentVariable(named = "JMIX_CLI_IT", matches = "true") @@ -28,7 +34,9 @@ class AgentToolkitInstallerIntegrationTest { @ParameterizedTest @ValueSource(strings = ["2.8.3", "3.0.1"]) fun `installs guidelines skills and MCP into the project`(jmixVersion: String) { - AgentToolkitInstaller.install(tempDir, jmixVersion) + // The lists are given, not taken from the live metadata: the expectations below are fixed. + val result = AgentToolkitInstaller.install(tempDir, jmixVersion, servers = mcpServers, agents = mcpAgents) + assertProjectRelative(result.changes) assertTrue(Files.isRegularFile(tempDir.resolve("CLAUDE.md")), "Claude guidelines must exist") assertEquals("@AGENTS.md\n", Files.readString(tempDir.resolve("CLAUDE.md"))) @@ -87,6 +95,94 @@ class AgentToolkitInstallerIntegrationTest { if (jetBrainsUrl.endsWith("/sse")) assertTrue(codex.contains("mcp-remote")) } + @ParameterizedTest + @ValueSource(strings = ["2.8.3", "3.0.1"]) + fun `the MCP step takes its servers and agents from the toolkit metadata by default`(jmixVersion: String) { + val result = AgentToolkitInstaller.install(tempDir, jmixVersion, steps = setOf(ToolkitStep.MCP)) + assertProjectRelative(result.changes) + // Every agent the metadata of the version's branch offers gets its project config. + val configs = AgentToolkitMetadata.mcpOptions(AgentToolkitInstaller.branch(jmixVersion)).agents.mapNotNull { it.projectConfig } + assertTrue(configs.isNotEmpty()) + for (config in configs) assertTrue(Files.isRegularFile(tempDir.resolve(config)), config) + } + + @Test + fun `a failed step stops the run with the installer's error`() { + Files.createDirectory(tempDir.resolve("AGENTS.md")) + val error = assertThrows(IOException::class.java) { + AgentToolkitInstaller.install( + tempDir, "3.0.1", steps = setOf(ToolkitStep.GUIDELINES, ToolkitStep.MCP), servers = mcpServers, agents = mcpAgents, + ) + } + val message = error.message.orEmpty() + assertTrue(message.startsWith("Agent Toolkit guidelines step failed: error: "), message) + assertEquals(listOf("AGENTS.md"), Files.list(tempDir).use { files -> files.map { it.fileName.toString() }.toList() }) + } + + @Test + fun `runs only the selected step, keeps own guidelines and reports the changes`() { + Files.writeString(tempDir.resolve("AGENTS.md"), "# Own rules\n") + val result = AgentToolkitInstaller.install(tempDir, "3.0.1", steps = setOf(ToolkitStep.GUIDELINES)) + assertEquals( + listOf("backed-up" to "AGENTS.md.bak", "updated" to "AGENTS.md", "created" to "CLAUDE.md"), + result.changes.map { it.action to it.path }, + ) + assertTrue(Files.readString(tempDir.resolve("AGENTS.md")).contains("# Own rules")) + assertFalse(Files.exists(tempDir.resolve(".agents"), NOFOLLOW_LINKS)) + assertFalse(Files.exists(tempDir.resolve(".mcp.json"), NOFOLLOW_LINKS)) + assertEquals(emptyList(), AgentToolkitInstaller.install(tempDir, "3.0.1", steps = setOf(ToolkitStep.GUIDELINES)).changes) + } + + @Test + fun `configures only the selected MCP servers and agents and relays the toolkit's notes`() { + val options = AgentToolkitMetadata.mcpOptions("v3") + val server = options.servers.last().value + val agent = options.agents.first().value + val result = AgentToolkitInstaller.install(tempDir, "3.0.1", steps = setOf(ToolkitStep.MCP), servers = listOf(server), agents = listOf(agent)) + val written = result.changes.single() + assertEquals("created", written.action) + assertTrue(Files.readString(tempDir.resolve(written.path)).contains(server)) + assertEquals(listOf(written.path), Files.list(tempDir).use { files -> files.map { it.fileName.toString() }.toList() }) + assertTrue(result.notes.isNotEmpty()) + assertTrue(result.notes.none { it.isBlank() || it.startsWith("[") || it.startsWith("@@") || it != it.trim() }) + } + + @Test + fun `a fresh install is up to date against the toolkit's own files`() { + // More patient than the production limit of a hint, which a slow runner would turn into a null state. + val fetch = { path: String -> AgentToolkitMetadata.fetch("v3", path, Duration.ofSeconds(30)) } + val missing = AgentToolkitStatus.State.NOT_INSTALLED + val current = AgentToolkitStatus.State.UP_TO_DATE + fun states() = AgentToolkitStatus.detect(tempDir, "v3", fetch).let { listOf(it.skills, it.guidelines, it.mcp) } + assertEquals(listOf(missing, missing, missing), states()) + val result = AgentToolkitInstaller.install(tempDir, "3.0.1", steps = setOf(ToolkitStep.SKILLS, ToolkitStep.GUIDELINES)) + assertEquals( + listOf("created" to ".agents/skills", "created" to ".claude/skills", "created" to "AGENTS.md", "created" to "CLAUDE.md"), + result.changes.map { it.action to it.path }, + ) + assertEquals(listOf(current, current, missing), states()) + // Junie alone: the toolkit gives it every server but JetBrains, and no user-level config is read. + AgentToolkitInstaller.install(tempDir, "3.0.1", steps = setOf(ToolkitStep.MCP), agents = listOf("junie")) + assertEquals(listOf(current, current, current), states()) + } + + @Test + fun `a Jmix major without a toolkit branch fails with its name`() { + val error = assertThrows(IOException::class.java) { AgentToolkitInstaller.install(tempDir, "99.0.0") } + assertEquals("the toolkit has no v99 branch for Jmix 99 yet", error.message) + } + + private val mcpServers = listOf("jetbrains", "jmix-docs", "playwright") + private val mcpAgents = listOf("claude", "codex", "opencode", "junie") + + private fun assertProjectRelative(changes: List) { + assertTrue(changes.isNotEmpty()) + for (change in changes) { + assertFalse(Path.of(change.path).isAbsolute, change.path) + assertTrue(Files.exists(tempDir.resolve(change.path), NOFOLLOW_LINKS), change.path) + } + } + private fun servers(config: String, key: String): JsonObject = JsonParser.parseString(Files.readString(tempDir.resolve(config))).asJsonObject.getAsJsonObject(key) } diff --git a/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerTest.kt b/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerTest.kt index 998e995..0626025 100644 --- a/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerTest.kt +++ b/src/test/kotlin/io/jmix/cli/env/AgentToolkitInstallerTest.kt @@ -1,10 +1,18 @@ package io.jmix.cli.env +import io.jmix.cli.WindowsConsole +import java.io.File import java.io.IOException +import java.nio.charset.Charset +import java.nio.file.FileSystems +import java.nio.file.Files import java.nio.file.Path import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir class AgentToolkitInstallerTest { @@ -26,6 +34,11 @@ class AgentToolkitInstallerTest { fun `rejects versions that do not start with a numeric major`() { assertThrows(IOException::class.java) { AgentToolkitInstaller.branch("evil'; touch pwned #") } assertThrows(IOException::class.java) { AgentToolkitInstaller.branch("latest") } + for (version in listOf("-1.0", "+3.x", "\u0663.0", "", ".5", "99999999999.0")) { + val error = assertThrows(IOException::class.java, { AgentToolkitInstaller.branch(version) }, version) + assertEquals("Unexpected Jmix version format: $version", error.message) + } + assertEquals("v3", AgentToolkitInstaller.branch("3")) } @Test @@ -44,29 +57,427 @@ class AgentToolkitInstallerTest { ) } + @Test + fun `steps get a PATH without empty or relative entries`(@TempDir dir: Path) { + val absolute = dir.toAbsolutePath().toString() + val path = listOf(absolute, "", ".", "bin", absolute).joinToString(File.pathSeparator) + assertEquals(listOf(absolute, absolute).joinToString(File.pathSeparator), AgentToolkitInstaller.trustedPath(path)) + assertEquals("", AgentToolkitInstaller.trustedPath(null)) + val home = System.getProperty("user.home") + assertEquals("$home/bin", AgentToolkitInstaller.trustedPath("~/bin")) + // Windows names the variable Path, and the environment map of a process is case-sensitive. + val environment = mutableMapOf("Path" to listOf(absolute, ".").joinToString(File.pathSeparator), "OTHER" to ".") + AgentToolkitInstaller.trustPathVariable(environment) + assertEquals(mapOf("Path" to absolute, "OTHER" to "."), environment) + } + @Test fun `runs the downloaded script as a file argument, never through a shell string`() { val script = Path.of("tmp", "toolkit.sh") + val powershell = "${System.getenv("SystemRoot") ?: "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" + val unix = AgentToolkitInstaller.command(script, AgentToolkitInstaller.guidelinesArgs(), os = "Linux") + // Never the bare name either: the JVM looks it up in PATH entries that can resolve inside the project. + assertTrue(unix.first() != "bash" && unix.first().endsWith("bash"), unix.first()) + assertEquals(listOf(script.toString(), "agents-md"), unix.drop(1)) assertEquals( - listOf("bash", script.toString(), "agents-md"), - AgentToolkitInstaller.command(script, AgentToolkitInstaller.guidelinesArgs(), os = "Linux"), - ) - assertEquals( - listOf("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script.toString()) + + listOf(powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script.toString()) + AgentToolkitInstaller.skillsArgs(os = "Windows 11"), AgentToolkitInstaller.command(script, AgentToolkitInstaller.skillsArgs(os = "Windows 11"), os = "Windows 11"), ) + // Never the bare name: Windows looks for that in the current directory, the project, first. + assertTrue(Regex("""[A-Za-z]:\\.*\\System32\\WindowsPowerShell\\v1\.0\\powershell\.exe""").matches(powershell), powershell) + } + + @Test + fun `mcp arguments carry the selected servers and agents`() { + assertEquals( + listOf("mcp", "--servers", "jmix-docs", "--agents", "claude,codex", "--scope", "local"), + AgentToolkitInstaller.mcpArgs(listOf("jmix-docs"), listOf("claude", "codex"), os = "Linux"), + ) + assertEquals( + listOf("mcp", "-Servers", "jmix-docs", "-Agents", "claude,codex", "-Scope", "local"), + AgentToolkitInstaller.mcpArgs(listOf("jmix-docs"), listOf("claude", "codex"), os = "Windows 11"), + ) + assertEquals("the toolkit has no v4 branch for Jmix 4 yet", AgentToolkitInstaller.missingBranchMessage("4.0.1")) + } + + @Test + fun `change markers become project-relative changes and the first action per path wins`(@TempDir dir: Path) { + val root = dir.toRealPath() + fun marker(action: String, path: Path) = "@@JMIX_CHANGE@@\taction=$action\ttype=file\tpath=$path" + val output = listOf( + "Installing skills into store", + marker("created", root.resolve(".mcp.json")), + marker("updated", root.resolve(".mcp.json")), + marker("backed-up", root.resolve("AGENTS.md.bak")), + marker("updated", root.resolve(".codex").resolve("config.toml")), + marker("moved-aside", root.resolve("a=b.txt")), + marker("moved_aside", root.resolve("Moved2.txt")), + marker("updated", root.resolveSibling("outside.json")), + marker("DROP TABLE", root.resolve("ignored.txt")), + "@@JMIX_CHANGE@@\taction=created", + ) + assertEquals( + listOf( + ToolkitChange("created", ".mcp.json"), + ToolkitChange("backed-up", "AGENTS.md.bak"), + ToolkitChange("updated", ".codex/config.toml"), + ToolkitChange("moved-aside", "a=b.txt"), + ToolkitChange("moved_aside", "Moved2.txt"), + ToolkitChange("updated", root.resolveSibling("outside.json").toString()), + ), + AgentToolkitInstaller.parseChanges(output, dir), + ) + } + + @Test + fun `a change path is cleaned, kept outside when it leaves the project, and dropped when empty`(@TempDir dir: Path) { + val root = dir.toRealPath() + val leaving = "$root/sub/../../outside" + val output = listOf( + "@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=$root/a\u0007b\u001B.txt", + "@@JMIX_CHANGE@@\taction=updated\ttype=file\tpath=$leaving", + "@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=", + "@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=\u0007", + ) + assertEquals( + listOf(ToolkitChange("created", "ab.txt"), ToolkitChange("updated", leaving)), + AgentToolkitInstaller.parseChanges(output, dir), + ) + } + + @Test + fun `notes are the toolkit's own guidance lines`() { + val reach = "IntelliJ IDEA MCP server is not reachable on port 64342; assuming IntelliJ IDEA 2026.1+." + val npx = "Note: Playwright starts through npx, which is not on PATH here. Install Node.js 20+ (https://nodejs.org) before using it." + val approve = "Claude Code asks to approve the servers in .mcp.json on its next start in this project." + val mcp = listOf( + "", reach, "", + "[JetBrains MCP] Claude CLI", " Created: /p/.mcp.json", + "@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=/p/.mcp.json", + "", npx, approve, approve, "Ring\u0007 the bell.", + "\u001B@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=/p/opencode.json", + ) + assertEquals(listOf(reach, npx, approve, "Ring the bell."), AgentToolkitInstaller.toolkitNotes(mcp, mcp = true)) + + val override = "Note: Codex reads /p/AGENTS.override.md instead of AGENTS.md there, so it does not see the Jmix block. Copy the block into it." + val guidelines = listOf("Project guidelines target directory: /p", " Installed: /p/AGENTS.md", " $override") + assertEquals(listOf(override), AgentToolkitInstaller.toolkitNotes(guidelines, mcp = false)) + } + + private val links get() = FileSystems.getDefault().supportedFileAttributeViews().contains("posix") + + private fun rejected(root: Path, vararg steps: ToolkitStep): String? = + assertThrows(IOException::class.java) { AgentToolkitInstaller.rejectLinkedPaths(root, steps.toSet()) }.message + + @Test + fun `a guidelines or skills path linked outside the project is rejected, for the selected steps only`( + @TempDir dir: Path, @TempDir outside: Path, + ) { + assumeTrue(links) + Files.createSymbolicLink(dir.resolve("CLAUDE.md"), Files.writeString(outside.resolve("credentials"), "secret")) + assertEquals( + "Cannot install Agent Toolkit guidelines through a path linked outside the project: CLAUDE.md.", + rejected(dir, ToolkitStep.GUIDELINES), + ) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS, ToolkitStep.MCP)) + + Files.createSymbolicLink(Files.createDirectories(dir.resolve(".agents")).resolve("skills"), outside) + assertEquals( + "Cannot install Agent Toolkit skills through a path linked outside the project: .agents/skills.", + rejected(dir, ToolkitStep.SKILLS), + ) + assertEquals( + "Cannot install Agent Toolkit skills through a path linked outside the project: .agents/skills.", + rejected(dir, *ToolkitStep.entries.toTypedArray()), + ) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.MCP)) + assertEquals("secret", Files.readString(outside.resolve("credentials"))) } @Test - fun `delegates local MCP setup to the toolkit for agents with project configs`() { + fun `a dangling link is judged by the target it would create`(@TempDir dir: Path, @TempDir outside: Path) { + assumeTrue(links) + // The toolkit's own layouts: CLAUDE.md -> AGENTS.md before AGENTS.md exists, Claude's skills after .agents is gone. + Files.createSymbolicLink(dir.resolve("CLAUDE.md"), Path.of("AGENTS.md")) + Files.createSymbolicLink(Files.createDirectories(dir.resolve(".claude")).resolve("skills"), Path.of("../.agents/skills")) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS, ToolkitStep.GUIDELINES)) + Files.delete(dir.resolve("CLAUDE.md")) + Files.createSymbolicLink(dir.resolve("AGENTS.md"), dir.resolve("missing.md")) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.GUIDELINES)) + + Files.delete(dir.resolve("AGENTS.md")) + Files.createSymbolicLink(dir.resolve("AGENTS.md"), outside.resolve("missing.md")) + val agents = "Cannot install Agent Toolkit guidelines through a path linked outside the project: AGENTS.md." + assertEquals(agents, rejected(dir, ToolkitStep.GUIDELINES)) + // A name followed by `..` could climb out of a linked folder, and a dangling link to one is not followed. + Files.createSymbolicLink(dir.resolve("linked"), outside) + for (target in listOf("linked/../missing.md", "next.md")) { + Files.delete(dir.resolve("AGENTS.md")) + Files.createSymbolicLink(dir.resolve("AGENTS.md"), Path.of(target)) + Files.deleteIfExists(dir.resolve("next.md")) + if (target == "next.md") Files.createSymbolicLink(dir.resolve("next.md"), Path.of("missing.md")) + assertEquals(agents, rejected(dir, ToolkitStep.GUIDELINES), target) + } + Files.delete(dir.resolve(".claude/skills")) + Files.createSymbolicLink(dir.resolve(".claude/skills"), Path.of("../linked/skills")) assertEquals( - listOf("mcp", "--servers", "jetbrains,jmix-docs,playwright", "--agents", "claude,codex,opencode,junie", "--scope", "local"), - AgentToolkitInstaller.mcpArgs(os = "Linux"), + "Cannot install Agent Toolkit skills through a path linked outside the project: .claude/skills.", + rejected(dir, ToolkitStep.SKILLS), ) + } + + @Test + fun `the skills guard covers every hidden folder's skills that the toolkit tidies`(@TempDir dir: Path, @TempDir outside: Path) { + assumeTrue(links) + // The toolkit tidies only `jmix*` entries there, so a linked folder without them is left alone. + Files.createDirectories(outside.resolve("junie/skills")) + Files.createDirectories(outside.resolve("team/skills/review")) + Files.createDirectories(outside.resolve("m2")) + Files.createSymbolicLink(dir.resolve(".m2"), outside.resolve("m2")) + Files.createSymbolicLink(dir.resolve(".team"), outside.resolve("team")) + Files.createDirectories(dir.resolve(".cursor/skills/jmix-old.bak1")) + Files.createSymbolicLink(dir.resolve(".junie"), outside.resolve("junie")) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS)) + Files.createDirectories(outside.resolve("junie/skills/jmix-old.bak1")) assertEquals( - listOf("mcp", "-Servers", "jetbrains,jmix-docs,playwright", "-Agents", "claude,codex,opencode,junie", "-Scope", "local"), - AgentToolkitInstaller.mcpArgs(os = "Windows 11"), + "Cannot install Agent Toolkit skills through a path linked outside the project: .junie/skills.", + rejected(dir, ToolkitStep.SKILLS), ) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.GUIDELINES)) + // install.ps1 also sweeps names that start with `..`. + Files.delete(dir.resolve(".junie")) + Files.createSymbolicLink(dir.resolve("..junie"), outside.resolve("junie")) + assertEquals( + "Cannot install Agent Toolkit skills through a path linked outside the project: ..junie/skills.", + rejected(dir, ToolkitStep.SKILLS), + ) + } + + @Test + fun `an MCP config name that differs only in letter case is no link`(@TempDir dir: Path) { + Files.writeString(dir.resolve("Opencode.json"), "{}") + // Only a case-insensitive disk (macOS, Windows) finds these under the toolkit's names. + assumeTrue(Files.exists(dir.resolve("opencode.json"))) + Files.createDirectories(dir.resolve(".Junie/MCP")) + AgentToolkitInstaller.rejectLinkedPaths(dir, ToolkitStep.entries.toSet()) + } + + @Test + fun `a Windows junction is a link to the guard`(@TempDir dir: Path, @TempDir outside: Path) { + assumeTrue(System.getProperty("os.name").startsWith("Windows")) + // The toolkit links folders with junctions on Windows, and to Java a junction is no symbolic link. + val junctions = mutableListOf() + fun junction(link: Path, target: Path) { + val process = ProcessBuilder("cmd", "/c", "mklink", "/J", link.toString(), target.toAbsolutePath().toString()) + .redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().readText() + assertEquals(0, process.waitFor(), output) + junctions.add(link) + } + try { + junction(Files.createDirectories(dir.resolve(".agents")).resolve("skills"), outside) + assertEquals( + "Cannot install Agent Toolkit skills through a path linked outside the project: .agents/skills.", + rejected(dir, ToolkitStep.SKILLS), + ) + junction(dir.resolve(".junie"), Files.createDirectories(dir.resolve("real/mcp")).parent) + assertEquals("Cannot configure project MCP servers through a linked path: .junie.", rejected(dir, ToolkitStep.MCP)) + Files.delete(junctions.removeAt(0)) + junction(Files.createDirectories(dir.resolve(".claude")).resolve("skills"), Files.createDirectories(dir.resolve(".agents/skills"))) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS)) + } finally { + // The junctions themselves go, so cleaning up the temporary folders never walks through them. + junctions.forEach(Files::deleteIfExists) + } + } + + @Test + fun `the MCP guard covers every project config of the toolkit's metadata and its folders`() { + val json = checkNotNull(javaClass.getResource("/toolkit/studio-meta-data-v3.json")).readText() + val configs = AgentToolkitMetadata.parseMcpOptions(json).agents.mapNotNull { it.projectConfig } + assertTrue(configs.isNotEmpty()) + val guarded = configs.flatMap { config -> config.split('/').runningReduce { folder, name -> "$folder/$name" } } + assertEquals(emptyList(), guarded.filterNot { it in AgentToolkitInstaller.MCP_PATHS }) + } + + @Test + fun `outside Windows a step without a usable PATH gets a fixed one, never the current directory`() { + for (environment in listOf(mutableMapOf("HOME" to "/h"), mutableMapOf("PATH" to ""), mutableMapOf("PATH" to ".${File.pathSeparator}bin"))) { + AgentToolkitInstaller.trustPathVariable(environment, os = "Linux") + assertEquals("/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", environment["PATH"], "$environment") + } + // Windows PowerShell never runs a bare name from the current directory, and Windows always has a Path. + val windows = mutableMapOf("Path" to ".") + AgentToolkitInstaller.trustPathVariable(windows, os = "Windows 11") + assertEquals(mapOf("Path" to ""), windows) + } + + @Test + fun `a step's environment has the markers, a trusted PATH, and Claude Desktop moved for MCP`(@TempDir profile: Path) { + fun prepared(os: String, mcp: Boolean) = mutableMapOf("PATH" to ".", "HOME" to "/home/u", "PSModulePath" to "pwsh").also { + AgentToolkitInstaller.prepareEnvironment(it, profile.takeIf { mcp }, os) + } + val skills = prepared("Linux", mcp = false) + assertEquals(mapOf("PATH" to "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", "HOME" to "/home/u", "JMIX_EMIT_CHANGE_MARKERS" to "1"), skills) + assertEquals("$profile", prepared("Linux", mcp = true)["XDG_CONFIG_HOME"]) + val mac = prepared("Mac OS X", mcp = true) + assertEquals("$profile", mac["HOME"]) + // The Codex conflict check keeps reading the real profile. + assertEquals(Path.of("/home/u", ".codex").toString(), mac["CODEX_HOME"]) + val windows = prepared("Windows 11", mcp = true) + assertEquals(listOf("$profile", "$profile"), listOf(windows["APPDATA"], windows["LOCALAPPDATA"])) + assertEquals("/home/u", windows["HOME"]) + } + + @Test + fun `a dangling link where the guidelines step would put a backup is rejected`(@TempDir dir: Path, @TempDir outside: Path) { + assumeTrue(links) + Files.writeString(dir.resolve("AGENTS.md"), "# Own rules\n") + Files.writeString(dir.resolve("AGENTS.md.bak"), "# Older rules\n") + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.GUIDELINES)) + Files.createSymbolicLink(dir.resolve("AGENTS.md.bak1"), outside.resolve("profile")) + assertEquals( + "Cannot install Agent Toolkit guidelines through a path linked outside the project: AGENTS.md.bak1.", + rejected(dir, ToolkitStep.GUIDELINES), + ) + } + + @Test + fun `links that stay inside the project pass the skills and guidelines guard`(@TempDir dir: Path) { + assumeTrue(links) + Files.writeString(dir.resolve("AGENTS.md"), "# Own rules\n") + Files.createSymbolicLink(dir.resolve("CLAUDE.md"), Path.of("AGENTS.md")) + Files.createDirectories(dir.resolve(".agents/skills")) + Files.createSymbolicLink(Files.createDirectories(dir.resolve(".claude")).resolve("skills"), Path.of("../.agents/skills")) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS, ToolkitStep.GUIDELINES)) + // Nothing to check in an empty project either. + AgentToolkitInstaller.rejectLinkedPaths(Files.createDirectories(dir.resolve("empty")), ToolkitStep.entries.toSet()) + } + + @Test + fun `any linked MCP config path is rejected, also when it stays inside the project`(@TempDir dir: Path) { + assumeTrue(links) + Files.createSymbolicLink(dir.resolve(".mcp.json"), Files.writeString(dir.resolve("real.json"), "{}")) + val message = "Cannot configure project MCP servers through a linked path: .mcp.json." + assertEquals(message, rejected(dir, ToolkitStep.MCP)) + assertEquals(message, rejected(dir, *ToolkitStep.entries.toTypedArray())) + AgentToolkitInstaller.rejectLinkedPaths(dir, setOf(ToolkitStep.SKILLS, ToolkitStep.GUIDELINES)) + + Files.delete(dir.resolve(".mcp.json")) + Files.createSymbolicLink(dir.resolve(".junie"), Files.createDirectories(dir.resolve("real/mcp")).parent) + assertEquals("Cannot configure project MCP servers through a linked path: .junie.", rejected(dir, ToolkitStep.MCP)) + } + + @Test + fun `install rejects linked paths before the download and the first step`(@TempDir dir: Path, @TempDir outside: Path) { + assumeTrue(links) + // Every phase is announced before it starts, so a run that got past the guard stops here, off the network. + fun rejectedInstall(steps: Set): String? = assertThrows(IOException::class.java) { + AgentToolkitInstaller.install(dir, "3.0.1", steps = steps, onStatus = { throw AssertionError("Not rejected before: $it") }) + }.message + + Files.createSymbolicLink(dir.resolve("CLAUDE.md"), Files.writeString(outside.resolve("credentials"), "secret")) + assertEquals( + "Cannot install Agent Toolkit guidelines through a path linked outside the project: CLAUDE.md.", + rejectedInstall(setOf(ToolkitStep.GUIDELINES)), + ) + + Files.delete(dir.resolve("CLAUDE.md")) + Files.createSymbolicLink(dir.resolve(".mcp.json"), Files.writeString(dir.resolve("real.json"), "{}")) + assertEquals( + "Cannot configure project MCP servers through a linked path: .mcp.json.", + rejectedInstall(ToolkitStep.entries.toSet()), + ) + } + + @Test + fun `a step log that is not valid UTF-8 is still read`(@TempDir dir: Path) { + val log = dir.resolve("step.log") + Files.write(log, byteArrayOf('o'.code.toByte(), 'k'.code.toByte(), '\n'.code.toByte(), 0xFF.toByte(), 'x'.code.toByte(), '\n'.code.toByte())) + val lines = AgentToolkitInstaller.readLog(log) + assertEquals(2, lines.size) + assertEquals("ok", lines[0]) + assertTrue(lines[1].endsWith("x")) + assertEquals(emptyList(), AgentToolkitInstaller.readLog(dir.resolve("missing.log"))) + } + + @Test + fun `a step log is read as UTF-8 when it is valid UTF-8, else in the fallback code page`(@TempDir dir: Path) { + val log = dir.resolve("step.log") + val oem = Charset.forName("IBM437") + Files.writeString(log, "café\n", Charsets.UTF_8) + assertEquals(listOf("café"), AgentToolkitInstaller.readLog(log, oem)) + // é is 0x82 in code page 437, no valid UTF-8. + Files.writeString(log, "café\n", oem) + assertEquals(listOf("café"), AgentToolkitInstaller.readLog(log, oem)) + assertEquals(listOf("caf�"), AgentToolkitInstaller.readLog(log, fallback = null)) + Files.write(log, byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + "ok\n".toByteArray()) + assertEquals(listOf("ok"), AgentToolkitInstaller.readLog(log, oem)) + } + + @Test + fun `a Windows PowerShell step's non-ASCII output is read in the code page it was written in`(@TempDir dir: Path) { + assumeTrue(System.getProperty("os.name").startsWith("Windows")) + // ASCII like install.ps1: the non-ASCII text comes from the project path, the working directory. + val script = Files.writeString( + dir.resolve("step.ps1"), + """ + Write-Output "cp=$([Console]::OutputEncoding.CodePage)" + Write-Output "@@JMIX_CHANGE@@`taction=created`ttype=file`tpath=$(Join-Path (Get-Location).Path '.mcp.json')" + Write-Output "Note: Codex reads $((Get-Location).Path)\AGENTS.override.md" + if (${'$'}args -contains 'fail') { [Console]::Error.WriteLine("error: cannot update $((Get-Location).Path)"); exit 1 } + """.trimIndent(), + ) + // A machine whose policy blocks scripts (AllSigned, Constrained Language) cannot run this check. + val probe = Files.writeString(dir.resolve("probe.ps1"), "[Console]::Error.WriteLine('ok')") + val runs = runCatching { AgentToolkitInstaller.runStep(dir, AgentToolkitInstaller.command(probe, emptyList()), "probe") } + assumeTrue(runs.getOrNull() == listOf("ok"), "PowerShell cannot run the test script here: $runs") + val project = Files.createDirectories(dir.resolve("café")).toRealPath() + val output = AgentToolkitInstaller.runStep(project, AgentToolkitInstaller.command(script, emptyList()), "test") + val codePage = output.first().removePrefix("cp=").toInt() + // A UTF-8 console has nothing to decode, and a code page without é loses it before the CLI reads it. + assumeTrue(codePage != 65001, "the child's console is UTF-8") + assumeTrue(WindowsConsole.charsetOf(codePage)?.newEncoder()?.canEncode('é') == true, "code page $codePage has no é") + // The one inferred link: Java's windowless child console starts in the OEM code page. + assertEquals(WindowsConsole.charsetOf(codePage), WindowsConsole.oemCharset, "child console code page $codePage vs GetOEMCP") + assertEquals(listOf(ToolkitChange("created", ".mcp.json")), AgentToolkitInstaller.parseChanges(output, project)) + assertEquals(listOf("Note: Codex reads $project\\AGENTS.override.md"), AgentToolkitInstaller.toolkitNotes(output, mcp = false)) + val failure = assertThrows(IOException::class.java) { + AgentToolkitInstaller.runStep(project, AgentToolkitInstaller.command(script, listOf("fail")), "test") + } + assertEquals("Agent Toolkit test step failed: error: cannot update $project", failure.message) + } + + @Test + fun `the failure tail of a step log carries no control characters`(@TempDir dir: Path) { + val log = dir.resolve("step.log") + Files.writeString(log, "Installing\n@@JMIX_CHANGE@@\taction=created\n\u001B[31mERROR:\u001B[0m no git\u0007\r\n") + assertEquals("Installing [31mERROR:[0m no git", AgentToolkitInstaller.logTail(log)) + assertEquals("no output", AgentToolkitInstaller.logTail(dir.resolve("missing.log"))) + } + + @Test + fun `a failed step is described by its error lines`(@TempDir dir: Path) { + val log = dir.resolve("step.log") + val followUps = (1..14).joinToString("\n") { "Follow-up $it" } + Files.writeString( + log, + "[Docs MCP] Codex\n \u001B[31merror: cannot parse /p/.codex/config.toml\u0007\r\n[Docs MCP] Junie\n Created: /p/x\n" + + "@@JMIX_CHANGE@@\taction=created\ttype=file\tpath=/p/x\nerror: second\n\n$followUps\n", + ) + // The escape character goes, so the first line no longer starts with the prefix: only real error lines count. + assertEquals("error: second", AgentToolkitInstaller.logTail(log)) + Files.writeString(log, "[Docs MCP] Codex\n error: cannot parse /p/.codex/config.toml\u0007\r\nerror: second\n\n$followUps\n") + assertEquals("error: cannot parse /p/.codex/config.toml error: second", AgentToolkitInstaller.logTail(log)) + Files.writeString(log, "error: " + "x".repeat(800) + "\n") + assertEquals(700, AgentToolkitInstaller.logTail(log).length) + } + + @Test + fun `a failed step without error lines is described by its last twelve non-blank lines`(@TempDir dir: Path) { + val log = dir.resolve("step.log") + Files.writeString(log, "first\n\n" + (1..12).joinToString("\n\n") { "line $it" } + "\n@@JMIX_CHANGE@@\taction=created\n\n") + assertEquals((1..12).joinToString(" ") { "line $it" }, AgentToolkitInstaller.logTail(log)) } } diff --git a/src/test/kotlin/io/jmix/cli/env/AgentToolkitMetadataTest.kt b/src/test/kotlin/io/jmix/cli/env/AgentToolkitMetadataTest.kt new file mode 100644 index 0000000..f0674b5 --- /dev/null +++ b/src/test/kotlin/io/jmix/cli/env/AgentToolkitMetadataTest.kt @@ -0,0 +1,152 @@ +package io.jmix.cli.env + +import io.jmix.cli.FakeServer +import java.io.FileNotFoundException +import java.io.IOException +import java.net.ServerSocket +import java.time.Duration +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertTimeoutPreemptively +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource + +class AgentToolkitMetadataTest { + + private val sample = """ + {"install-flow":{"steps":[ + {"id":"skills","inputs":[{"id":"mcpServers","type":"options","choices":[{"value":"wrong-step","default":true}]}]}, + {"id":"mcp","inputs":[ + {"id":"mcpScope","type":"options","choices":[{"value":"local","label":"Local","default":true},{"value":"global","label":"Global"}]}, + {"id":"mcpServers","type":"options","multi":true,"choices":[ + {"value":"alpha","label":"Al\u001Bpha","default":true}, + {"value":"keyed","label":"Keyed","default":true}, + {"value":"key-ed","label":"Hyphen","default":true}, + {"value":"my_docs","label":"Underscore","default":true}, + {"value":"beta","default":true}, + {"value":"off","label":"Off","default":false}, + {"value":"bad value","label":"Bad","default":true}, + {"value":"--flag","label":"Flag","default":true}]}, + {"id":"mcpAgents","type":"options","multi":true,"choices":[ + {"value":"one","label":"One","default":true}, + {"value":"two","label":"Two"}, + {"value":"three","label":" ","default":true}]}, + {"id":"KeyedToken","type":"userInput","default":"skip"}, + {"id":"keyEdSecret","type":"userInput"}, + {"id":"my_docsKey","type":"userInput"}, + {"id":"alphaNote","type":"options","choices":[]}]}]}} + """.trimIndent() + + @Test + fun `offers the default choices and drops servers that need a text input`() { + val options = AgentToolkitMetadata.parseMcpOptions(sample) + assertEquals(listOf(ToolkitChoice("alpha", "Alpha"), ToolkitChoice("beta", "beta")), options.servers) + assertEquals(listOf(ToolkitChoice("one", "One"), ToolkitChoice("three", "three")), options.agents) + } + + @Test + fun `the toolkit v3 metadata gives the lists jmix new used to hardcode`() { + val json = checkNotNull(javaClass.getResource("/toolkit/studio-meta-data-v3.json")).readText() + val options = AgentToolkitMetadata.parseMcpOptions(json) + assertEquals(listOf("jetbrains", "jmix-docs", "playwright"), options.servers.map { it.value }) + assertEquals(listOf("JetBrains", "Jmix Docs", "Playwright"), options.servers.map { it.label }) + assertEquals(listOf("claude", "codex", "opencode", "junie"), options.agents.map { it.value }) + assertEquals(listOf("Claude Code", "Codex", "OpenCode", "Junie"), options.agents.map { it.label }) + assertEquals(listOf(".mcp.json", ".codex/config.toml", "opencode.json", ".junie/mcp/mcp.json"), options.agents.map { it.projectConfig }) + assertEquals(listOf(emptyList(), emptyList(), emptyList(), listOf("jetbrains")), options.agents.map { it.skipServers }) + } + + @Test + fun `an agent's skipped servers are the strings of its skipServers array`() { + fun agent(value: String, skip: String) = """{"value":"$value","default":true,"skipServers":$skip}""" + val agents = listOf(agent("list", """["jetbrains", 5, null, "x"]"""), agent("text", "\"jetbrains\""), """{"value":"none","default":true}""") + val servers = """{"id":"mcpServers","type":"options","choices":[{"value":"s","default":true}]}""" + val json = """{"install-flow":{"steps":[{"id":"mcp","inputs":[$servers,{"id":"mcpAgents","type":"options","choices":[${agents.joinToString(",")}]}]}]}}""" + val skips = AgentToolkitMetadata.parseMcpOptions(json).agents.associate { it.value to it.skipServers } + assertEquals(mapOf("list" to listOf("jetbrains", "x"), "text" to emptyList(), "none" to emptyList()), skips) + } + + @Test + fun `an agent's project config is kept only as a plain relative path`() { + fun agent(value: String, config: String) = """{"value":"$value","default":true,"projectConfig":$config}""" + val agents = listOf( + agent("plain", "\".mcp.json\""), agent("nested", "\".junie/mcp/mcp.json\""), """{"value":"none","default":true}""", + agent("absolute", "\"/etc/mcp.json\""), agent("parent", "\"a/../../mcp.json\""), agent("dot", "\"./mcp.json\""), + agent("backslash", "\"a\\\\b.json\""), agent("empty", "\"\""), agent("number", "5"), + ) + val servers = """{"id":"mcpServers","type":"options","choices":[{"value":"s","default":true}]}""" + val json = """{"install-flow":{"steps":[{"id":"mcp","inputs":[$servers,{"id":"mcpAgents","type":"options","choices":[${agents.joinToString(",")}]}]}]}}""" + val configs = AgentToolkitMetadata.parseMcpOptions(json).agents.associate { it.value to it.projectConfig } + assertEquals(mapOf("plain" to ".mcp.json", "nested" to ".junie/mcp/mcp.json"), configs.filterValues { it != null }) + assertEquals(9, configs.size) + } + + @ParameterizedTest + @ValueSource(strings = [ + "not json", + "[]", + "{}", + """{"install-flow":{"steps":[1]}}""", + """{"install-flow":{"steps":[{"id":"mcp","inputs":[null]}]}}""", + """{"install-flow":{"steps":[{"id":"skills","inputs":[]}]}}""", + """{"install-flow":{"steps":[{"id":"mcp","inputs":[{"id":"mcpServers","type":"options","choices":[{"value":"a","default":true}]}]}]}}""", + """{"install-flow":{"steps":[{"id":"mcp","inputs":[{"id":"mcpServers","type":"options","choices":[{"value":"a","default":false}]},{"id":"mcpAgents","type":"options","choices":[{"value":"b","default":true}]}]}]}}""", + """{"install-flow":{"steps":[{"id":"mcp","inputs":[{"id":"mcpServers","type":"options","choices":"a"},{"id":"mcpAgents","type":"options","choices":[{"value":"b","default":true}]}]}]}}""", + ]) + fun `unexpected metadata is rejected`(json: String) { + val error = assertThrows(IOException::class.java) { AgentToolkitMetadata.parseMcpOptions(json) } + assertEquals("Unexpected Agent Toolkit metadata format.", error.message) + } + + @Test + fun `a choice with a value that is no text or a default that is no boolean is not offered`() { + fun input(id: String, vararg choices: String) = """{"id":"$id","type":"options","choices":[${choices.joinToString(",")}]}""" + val ok = """{"value":"ok","default":true}""" + val servers = input("mcpServers", """{"value":5,"default":"true"}""", """{"value":5,"default":true}""", """{"value":"text","default":"true"}""", ok) + val options = AgentToolkitMetadata.parseMcpOptions("""{"install-flow":{"steps":[{"id":"mcp","inputs":[$servers,${input("mcpAgents", ok)}]}]}}""") + assertEquals(listOf(ToolkitChoice("ok", "ok")), options.servers) + } + + @Test + fun `fetch reads a toolkit file and names the one it cannot read`() { + FakeServer().use { server -> + server.on("GET", "/v3/.studio/studio-meta-data.json") { FakeServer.Response(200, sample.toByteArray()) } + server.on("GET", "/v3/big.json") { FakeServer.Response(200, ByteArray(256 * 1024 + 1)) } + server.on("GET", "/v3/broken.json") { FakeServer.Response(500) } + val limit = Duration.ofSeconds(5) + assertEquals(sample, AgentToolkitMetadata.fetch("v3", ".studio/studio-meta-data.json", limit, base = server.url)) + assertEquals(listOf("alpha", "beta"), AgentToolkitMetadata.mcpOptions("v3", limit, base = server.url).servers.map { it.value }) + val missing = assertThrows(FileNotFoundException::class.java) { AgentToolkitMetadata.fetch("v3", "missing.json", limit, base = server.url) } + assertEquals("Cannot load missing.json from Agent Toolkit v3: HTTP 404", missing.message) + val broken = assertThrows(IOException::class.java) { AgentToolkitMetadata.fetch("v3", "broken.json", limit, base = server.url) } + assertEquals("Cannot load broken.json from Agent Toolkit v3: HTTP 500", broken.message) + assertFalse(broken is FileNotFoundException) + val big = assertThrows(IOException::class.java) { AgentToolkitMetadata.fetch("v3", "big.json", limit, base = server.url) } + assertTrue(big.message.orEmpty().startsWith("Cannot load big.json from Agent Toolkit v3: "), big.message) + assertFalse(big is FileNotFoundException) + } + } + + @Test + fun `fetch gives up at its timeout`() { + FakeServer().use { server -> + server.on("GET", "/v3/slow.json") { Thread.sleep(3_000); FakeServer.Response(200, "late".toByteArray()) } + val error = assertTimeoutPreemptively(Duration.ofMillis(2_500)) { + assertThrows(IOException::class.java) { AgentToolkitMetadata.fetch("v3", "slow.json", Duration.ofSeconds(1), base = server.url) } + } + assertEquals("Cannot load slow.json from Agent Toolkit v3: cannot reach 127.0.0.1", error.message) + } + } + + @Test + fun `fetch names the file when the toolkit host does not answer`() { + val port = ServerSocket(0).use { it.localPort } + val error = assertThrows(IOException::class.java) { + AgentToolkitMetadata.fetch("v3", "any.json", Duration.ofSeconds(5), base = "http://127.0.0.1:$port") + } + assertEquals("Cannot load any.json from Agent Toolkit v3: cannot reach 127.0.0.1", error.message) + } +} diff --git a/src/test/kotlin/io/jmix/cli/env/AgentToolkitStatusTest.kt b/src/test/kotlin/io/jmix/cli/env/AgentToolkitStatusTest.kt new file mode 100644 index 0000000..89170e0 --- /dev/null +++ b/src/test/kotlin/io/jmix/cli/env/AgentToolkitStatusTest.kt @@ -0,0 +1,278 @@ +package io.jmix.cli.env + +import java.io.IOException +import java.io.RandomAccessFile +import java.nio.file.FileSystems +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assumptions.assumeFalse +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource + +class AgentToolkitStatusTest { + @TempDir lateinit var dir: Path + + private val manifestPath = ".studio/skills-manifest.json" + private val blockPath = "content/guidelines-block.md" + private val sha = "10ac7c357bf35ade8fbc86f552bf92eddd77adfb118d225dd50c87627a36535d" + private val block = "\n## Jmix\n\nRead the skill.\n\n" + + private fun manifest(hash: String = sha, store: String = "store/skills") = + """{"schemaVersion":1,"sha256":"$hash","skills":["jmix","jmix-b","jmix-missing"],"store":{"global":".g","local":"$store"}}""" + + private fun skill(name: String, vararg files: Pair) = files.forEach { (path, text) -> + val file = dir.resolve("store/skills").resolve(name).resolve(path) + Files.createDirectories(file.parent) + Files.writeString(file, text) + } + + private fun fixture() { + skill("jmix", "SKILL.md" to "a\n") + skill("jmix-b", "SKILL.md" to "b\n", "ref/x.txt" to "x") + } + + private val metadataPath = ".studio/studio-meta-data.json" + private val metadataV3 = checkNotNull(javaClass.getResource("/toolkit/studio-meta-data-v3.json")).readText() + + private fun detect( + manifest: String? = manifest(), + block: String? = this.block, + metadata: String? = metadataV3, + ): AgentToolkitStatus.Status { + // The files are fetched at once, from several threads. + val asked = ConcurrentLinkedQueue() + val status = AgentToolkitStatus.detect(dir, "v3") { path -> + asked += path + when (path) { manifestPath -> manifest; blockPath -> block; metadataPath -> metadata; else -> error(path) } + } + assertEquals(setOf(manifestPath, blockPath, metadataPath), asked.toSet()) + return status + } + + private fun config(path: String, text: String) { + val file = dir.resolve(path) + Files.createDirectories(file.parent) + Files.writeString(file, text) + } + + private fun agentsMd(text: String) = Files.writeString(dir.resolve("AGENTS.md"), text) + + @Test + fun `skills hash matches the toolkit manifest algorithm`() { + fixture() + assertEquals(sha, AgentToolkitStatus.skillsHash(dir.resolve("store/skills"), listOf("jmix-missing", "jmix-b", "jmix"))) + } + + @Test + fun `skills are missing, up to date or outdated against the manifest`() { + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().skills) + fixture() + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().skills) + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect(manifest("0".repeat(64))).skills) + } + + @Test + fun `guidelines are missing, up to date or outdated against the block`() { + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().guidelines) + agentsMd("# Own rules\n") + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().guidelines) + agentsMd("Never write by hand.\n") + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().guidelines) + agentsMd("# Own rules\r\n\r\n" + block.replace("\n", "\r\n")) + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().guidelines) + agentsMd("\uFEFF" + block.replace("Read the skill.", "Old text.")) + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().guidelines) + } + + @Test + fun `MCP is set up when one agent's project config names every offered server`() { + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().mcp) + // A config of the project's own, with no server of the toolkit. + config(".mcp.json", """{"mcpServers":{"mine":{"url":"http://mine"}}}""") + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().mcp) + // Two of the three servers, one of them only as a value. + config(".mcp.json", """{"mcpServers":{"jetbrains":{},"jmix-docs":{"url":"playwright"}}}""") + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().mcp) + // The third one in another agent's config: together they name all three, but each agent misses one. + config("opencode.json", """{"mcp":{"playwright":{}}}""") + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().mcp) + // A TOML config that names all three. + config(".codex/config.toml", "[mcp_servers.jetbrains]\n[mcp_servers.\"jmix-docs\"]\n [mcp_servers.playwright]\ncommand = \"npx\"\n") + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + // The JSON config alone, once complete. + Files.delete(dir.resolve(".codex/config.toml")) + config(".mcp.json", """{"mcpServers":{"jetbrains":{},"jmix-docs":{},"playwright" : {}}}""") + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + } + + @Test + fun `a Junie config is complete without the servers the toolkit never gives Junie`() { + config(".junie/mcp/mcp.json", """{"mcpServers":{"jmix-docs":{}}}""") + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().mcp) + // What the installers write for Junie: every server but JetBrains. + config(".junie/mcp/mcp.json", """{"mcpServers":{"jmix-docs":{},"playwright":{}}}""") + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + // Without the toolkit's exception, the JetBrains server would be missing. + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect(metadata = metadataV3.replace("skipServers", "otherKey")).mcp) + } + + @Test + fun `TOML table headers count as the installers read them`() { + config(".codex/config.toml", "[mcp_servers.jetbrains]\n[ mcp_servers . 'jmix-docs' ]\r\n[\"mcp_servers\".\"playwright\"]\n") + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + // A commented-out table is not a server. + config(".codex/config.toml", "[mcp_servers.jetbrains]\n[mcp_servers.jmix-docs]\n# [mcp_servers.playwright]\n") + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().mcp) + } + + @Test + fun `MCP has no state without agent project configs or with unreadable metadata`() { + config(".mcp.json", """{"mcpServers":{"jetbrains":{},"jmix-docs":{},"playwright":{}}}""") + assertNull(detect(metadata = metadataV3.replace("projectConfig", "otherKey")).mcp) + assertNull(detect(metadata = "not json").mcp) + assertNull(detect(metadata = null).mcp) + } + + @Test + fun `the three files are requested at once`() { + val started = CountDownLatch(3) + val waitedAlone = AtomicBoolean(false) + AgentToolkitStatus.detect(dir, "v3") { path -> + started.countDown() + // One request after another, each would wait here alone. + if (!started.await(5, TimeUnit.SECONDS)) waitedAlone.set(true) + when (path) { manifestPath -> manifest(); blockPath -> block; else -> metadataV3 } + } + assertFalse(waitedAlone.get()) + } + + @Test + fun `the MCP choices come with the status`() { + assertEquals(AgentToolkitMetadata.parseMcpOptions(metadataV3), detect().mcpOptions) + assertNull(detect(metadata = "not json").mcpOptions) + } + + @Test + fun `a config that is not UTF-8 is still read`() { + val names = """{"mcpServers":{"jetbrains":{},"jmix-docs":{},"playwright":{}},"note":"""" + Files.write(dir.resolve(".mcp.json"), names.toByteArray() + byteArrayOf(0xC3.toByte(), 0x28) + "\"}".toByteArray()) + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + } + + @Test + fun `a config that cannot be read leaves the state to the others`() { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val locked = dir.resolve(".mcp.json") + Files.writeString(locked, """{"mcpServers":{"jetbrains":{}}}""") + Files.setPosixFilePermissions(locked, emptySet()) + assumeFalse(Files.isReadable(locked), "this user reads every file") + assertNull(detect().mcp) + config("opencode.json", """{"mcp":{"jetbrains":{}}}""") + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().mcp) + config("opencode.json", """{"mcp":{"jetbrains":{},"jmix-docs":{},"playwright":{}}}""") + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + } + + @Test + fun `an MCP config over the size limit is not read`() { + config(".mcp.json", """{"mcpServers":{"jetbrains":{},"jmix-docs":{},"playwright":{}}}""") + // Sparse: the length is set without writing 4 MiB. + RandomAccessFile(dir.resolve(".mcp.json").toFile(), "rw").use { it.setLength(4L * 1024 * 1024 + 1) } + assertNull(detect().mcp) + RandomAccessFile(dir.resolve(".mcp.json").toFile(), "rw").use { it.setLength(4L * 1024 * 1024) } + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().mcp) + } + + @Test + fun `an MCP config linked outside the project is not read`(@TempDir outside: Path) { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val target = Files.writeString(outside.resolve("mcp.json"), """{"jetbrains":{},"jmix-docs":{},"playwright":{}}""") + Files.createSymbolicLink(dir.resolve(".mcp.json"), target) + assertEquals(AgentToolkitStatus.State.NOT_INSTALLED, detect().mcp) + } + + @Test + fun `hints are omitted when the toolkit cannot be read`() { + fixture() + assertEquals(AgentToolkitStatus.Status(null, null), detect(manifest = null, block = null, metadata = null)) + assertEquals(AgentToolkitStatus.Status(null, null), detect(manifest = "not json", block = " \n", metadata = "{}")) + assertNull(detect(manifest = """{"sha256":"$sha","skills":"jmix","store":{"local":"store/skills"}}""").skills) + assertEquals( + AgentToolkitStatus.Status(null, null), + AgentToolkitStatus.detect(dir, "v3") { throw IOException("offline") }, + ) + } + + @ParameterizedTest + @ValueSource(strings = ["../outside", "/abs/skills", "store/../../outside", ""]) + fun `a manifest that points outside the project is ignored`(store: String) { + fixture() + assertNull(detect(manifest(store = store)).skills) + } + + @Test + fun `a guidelines file over the size limit is not read`() { + agentsMd(block) + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().guidelines) + // Sparse: the length is set without writing 4 MiB. + RandomAccessFile(dir.resolve("AGENTS.md").toFile(), "rw").use { it.setLength(4L * 1024 * 1024 + 1) } + assertNull(detect().guidelines) + RandomAccessFile(dir.resolve("AGENTS.md").toFile(), "rw").use { it.setLength(4L * 1024 * 1024) } + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().guidelines) + } + + @Test + fun `a skills store linked outside the project is not read`(@TempDir outside: Path) { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + fixture() + Files.move(dir.resolve("store"), outside.resolve("store")) + Files.createSymbolicLink(dir.resolve("store"), outside.resolve("store")) + assertNull(detect().skills) + Files.delete(dir.resolve("store")) + Files.move(outside.resolve("store"), dir.resolve("real")) + Files.createSymbolicLink(dir.resolve("store"), dir.resolve("real")) + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().skills) + } + + @Test + fun `a guidelines file that is not UTF-8 is still read`() { + // The installers keep the user's own bytes, here Latin-1, below the block they add. + Files.write(dir.resolve("AGENTS.md"), block.toByteArray() + "\n# Caf".toByteArray() + byteArrayOf(0xE9.toByte(), '\n'.code.toByte())) + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect().guidelines) + } + + @Test + fun `a guidelines file linked outside the project is not read`(@TempDir outside: Path) { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + Files.createSymbolicLink(dir.resolve("AGENTS.md"), Files.writeString(outside.resolve("AGENTS.md"), block)) + assertNull(detect().guidelines) + } + + @Test + fun `a link in a skill folder is never read, so a replaced toolkit file counts as changed`(@TempDir outside: Path) { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + fixture() + val skill = dir.resolve("store/skills/jmix/SKILL.md") + Files.move(skill, outside.resolve("SKILL.md")) + Files.createSymbolicLink(skill, outside.resolve("SKILL.md")) + assertEquals(AgentToolkitStatus.State.UPDATE_AVAILABLE, detect().skills) + } + + @Test + fun `skill names that are not plain names are not followed`() { + fixture() + Files.writeString(Files.createDirectories(dir.resolve("store/secret")).resolve("f"), "s") + val manifest = """{"sha256":"$sha","skills":["jmix","jmix-b","../secret"],"store":{"local":"store/skills"}}""" + assertEquals(AgentToolkitStatus.State.UP_TO_DATE, detect(manifest).skills) + } +} diff --git a/src/test/kotlin/io/jmix/cli/trial/TrialArchiveTest.kt b/src/test/kotlin/io/jmix/cli/trial/TrialArchiveTest.kt index e58ff8d..9c66a2a 100644 --- a/src/test/kotlin/io/jmix/cli/trial/TrialArchiveTest.kt +++ b/src/test/kotlin/io/jmix/cli/trial/TrialArchiveTest.kt @@ -283,6 +283,59 @@ class TrialArchiveTest { assertNull(TrialArchive.jmixVersion(legacy)) } + @Test + fun `jmix version falls back to the io_jmix plugin version`() { + val groovy = Files.createDirectories(dir.resolve("groovy")) + Files.writeString(groovy.resolve("build.gradle"), "plugins {\n id 'io.jmix' version '3.1.0'\n}\njmix {\n bomVersion = version\n}\n") + assertEquals("3.1.0", TrialArchive.jmixVersion(groovy)) + val kotlin = Files.createDirectories(dir.resolve("kotlin")) + Files.writeString(kotlin.resolve("build.gradle.kts"), "plugins {\n id(\"io.jmix\") version \"2.8.3\"\n}\n") + assertEquals("2.8.3", TrialArchive.jmixVersion(kotlin)) + val unsafe = Files.createDirectories(dir.resolve("unsafe")) + Files.writeString(unsafe.resolve("build.gradle"), "plugins { id 'io.jmix' version '\$(touch x)' }") + assertNull(TrialArchive.jmixVersion(unsafe)) + } + + @Test + fun `a value that is not a version is skipped`() { + val project = Files.createDirectories(dir.resolve("interpolated")) + Files.writeString(project.resolve("build.gradle"), "plugins {\n id 'io.jmix' version '3.1.0'\n}\njmix {\n bomVersion = \"\${jmixVersion}\"\n}\n") + assertEquals("3.1.0", TrialArchive.jmixVersion(project)) + Files.writeString(project.resolve("build.gradle"), "jmix { bomVersion = \"\${v}\" }\next { bomVersion = '3.2.0' }\n") + assertEquals("3.2.0", TrialArchive.jmixVersion(project)) + Files.writeString(project.resolve("build.gradle"), "plugins { id 'io.jmix' version '3.1.0.trial' }") + assertEquals("3.1.0", TrialArchive.jmixVersion(project)) + Files.writeString(project.resolve("build.gradle"), "plugins { rapid 'io.jmix' version '3.1.0' }") + assertNull(TrialArchive.jmixVersion(project)) + } + + @Test + fun `version detection is not slowed down by a hostile build file`() { + val project = Files.createDirectories(dir.resolve("hostile")) + Files.writeString(project.resolve("build.gradle"), ("id" + " ".repeat(40_000) + "x\n").repeat(20)) + assertNull(assertTimeoutPreemptively(Duration.ofSeconds(2)) { TrialArchive.jmixVersion(project) }) + } + + @Test + fun `a build file that is not a regular file is not opened`() { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val project = Files.createDirectories(dir.resolve("pipe")) + // Opening a pipe for reading waits for a writer that never comes. + assumeTrue(runCatching { ProcessBuilder("mkfifo", project.resolve("build.gradle").toString()).start().waitFor() == 0 }.getOrDefault(false)) + Files.writeString(project.resolve("build.gradle.kts"), "plugins { id(\"io.jmix\") version \"2.8.3\" }") + assertEquals("2.8.3", assertTimeoutPreemptively(Duration.ofSeconds(2)) { TrialArchive.jmixVersion(project) }) + } + + @Test + fun `a literal bomVersion wins over a plugin version, also from a later build file`() { + val project = Files.createDirectories(dir.resolve("both")) + Files.writeString(project.resolve("build.gradle"), "plugins { id 'io.jmix' version '3.0.0' }\njmix { bomVersion = '3.1.0' }") + assertEquals("3.1.0", TrialArchive.jmixVersion(project)) + val composite = TrialArchive.unpack(trialZip(), dir.resolve("work")).single() + Files.writeString(composite.resolve("build.gradle"), "plugins { id 'io.jmix' version '3.0.0' }") + assertEquals("3.1.0", TrialArchive.jmixVersion(composite)) + } + @Test fun `runnable apps are the demos, or the project itself without demos`() { val project = TrialArchive.unpack(trialZip(), dir.resolve("work")).single() diff --git a/src/test/kotlin/io/jmix/cli/wizard/PromptsTest.kt b/src/test/kotlin/io/jmix/cli/wizard/PromptsTest.kt index a4c12b5..534f710 100644 --- a/src/test/kotlin/io/jmix/cli/wizard/PromptsTest.kt +++ b/src/test/kotlin/io/jmix/cli/wizard/PromptsTest.kt @@ -977,6 +977,22 @@ class PromptsTest { assertTrue(recorder.output().contains("IdeaProjects IdeaSettings")) } + @Test + fun `with exitOnEof Ctrl+D in a numbered checklist aborts, and the end of piped input fails`() { + for (interactive in listOf(true, false)) withEmptyStdin { + val recorder = TerminalRecorder(width = 80, height = 20, inputInteractive = interactive) + // An IDE console when interactive: keyboard input, but no raw mode. + val console = object : TerminalInterface by recorder { + override fun enterRawMode(mouseTracking: MouseTracking): AutoCloseable = throw IllegalStateException("no raw mode") + } + val prompts = Prompts(Terminal(terminalInterface = console), exitOnEof = true, eofError = "No input.") + val error = assertThrows(CliktError::class.java) { + prompts.chooseMany("Steps", listOf(SelectList.Entry("skills")), filterTexts = listOf("skills")) + } + assertEquals(if (interactive) "Aborted." else "No input.", error.message) + } + } + private fun withEmptyStdin(block: () -> Unit) = withStdin("", block) private fun withStdin(input: String, block: () -> Unit) { diff --git a/src/test/resources/toolkit/studio-meta-data-v3.json b/src/test/resources/toolkit/studio-meta-data-v3.json new file mode 100644 index 0000000..c08ba19 --- /dev/null +++ b/src/test/resources/toolkit/studio-meta-data-v3.json @@ -0,0 +1,182 @@ +{ + "$schema": "./studio-meta-data.schema.json", + "install-flow": { + "steps": [ + { + "id": "skills", + "title": "Skills", + "message": "🛠️ Install Jmix skills in the project or the user home.
📁 Agents find them in .agents/skills: Codex, OpenCode, Junie, Cline, Cursor, GitHub Copilot, Gemini CLI and others. For Claude Code, each skill is also linked into .claude/skills.
⏭️ Click Skip to opt out.", + "inputs": [ + { + "id": "skillsScope", + "label": "Installation scope", + "type": "options", + "choices": [ + { + "value": "local", + "label": "Local (project)", + "default": true + }, + { + "value": "global", + "label": "Global (user home)" + } + ] + }, + { + "id": "skillsClaude", + "label": "🤖 Claude Code", + "type": "options", + "choices": [ + { + "value": "true", + "label": "Yes, also link into .claude/skills", + "default": true + }, + { + "value": "false", + "label": "No, .agents/skills only" + } + ] + } + ], + "command": { + "windows": "& ([scriptblock]::Create((iwr -useb https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.ps1).Content)) skills -ContentRef \"${guidelinesBranch}\" -Scope \"${skillsScope}\" -Claude:$${skillsClaude}", + "macos": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- skills --content-ref \"${guidelinesBranch}\" --scope \"${skillsScope}\" --claude=\"${skillsClaude}\"", + "linux": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- skills --content-ref \"${guidelinesBranch}\" --scope \"${skillsScope}\" --claude=\"${skillsClaude}\"" + } + }, + { + "id": "guidelines", + "title": "Guidelines", + "message": "📘 Add a few lines to AGENTS.md that point the agents at the Jmix skills. For Claude Code, a new CLAUDE.md contains only @AGENTS.md to share these instructions.
✍️ Your own instructions are kept — the lines are merged in. A guidelines file installed by an older version of this toolkit is replaced instead. Changed user or legacy files are backed up. If CLAUDE.md imports @AGENTS.md, it is left untouched after AGENTS.md is updated.
⏭️ Click Skip to leave the project as is; the Jmix skills are then installed but nothing routes the agents to them.", + "inputs": [ + { + "id": "guidelinesClaude", + "label": "🤖 Claude Code", + "type": "options", + "choices": [ + { + "value": "true", + "label": "Yes, also CLAUDE.md", + "default": true + }, + { + "value": "false", + "label": "No, AGENTS.md only" + } + ] + } + ], + "command": { + "windows": "& ([scriptblock]::Create((iwr -useb https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.ps1).Content)) agents-md -ContentRef \"${guidelinesBranch}\" -Claude:$${guidelinesClaude}", + "macos": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- agents-md --content-ref \"${guidelinesBranch}\" --claude=\"${guidelinesClaude}\"", + "linux": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- agents-md --content-ref \"${guidelinesBranch}\" --claude=\"${guidelinesClaude}\"" + } + }, + { + "id": "mcp", + "title": "MCP servers", + "message": "🔌 Connect the agents to MCP servers:
🧩 JetBrains: enable the MCP server in IntelliJ IDEA (Settings | Tools | MCP Server).
📚 Context7: get a key on context7.com. With Local, it is saved in the project files: keep them out of Git.
📖 Jmix Docs: Jmix documentation, Java API and UI samples.
🎭 Playwright: needs Node.js 20+.
🤖 Cline has no project config: its user config is written with either scope.
⏭️ Click Skip to opt out.", + "inputs": [ + { + "id": "mcpScope", + "label": "Scope", + "type": "options", + "choices": [ + { + "value": "local", + "label": "Local (project files)", + "default": true + }, + { + "value": "global", + "label": "Global (user config)" + } + ] + }, + { + "id": "mcpServers", + "label": "🔌 MCP Servers:", + "type": "options", + "multi": true, + "choices": [ + { + "value": "jetbrains", + "label": "JetBrains", + "default": true + }, + { + "value": "context7", + "label": "Context7", + "default": true + }, + { + "value": "jmix-docs", + "label": "Jmix Docs", + "default": true + }, + { + "value": "playwright", + "label": "Playwright", + "default": true + } + ] + }, + { + "id": "mcpAgents", + "label": "🤖 Agents", + "type": "options", + "multi": true, + "choices": [ + { + "value": "claude", + "label": "Claude Code", + "default": true, + "projectConfig": ".mcp.json" + }, + { + "value": "codex", + "label": "Codex", + "default": true, + "projectConfig": ".codex/config.toml" + }, + { + "value": "opencode", + "label": "OpenCode", + "default": true, + "projectConfig": "opencode.json" + }, + { + "value": "junie", + "label": "Junie", + "default": true, + "projectConfig": ".junie/mcp/mcp.json", + "skipServers": ["jetbrains"] + }, + { + "value": "cline", + "label": "Cline", + "default": false + } + ] + }, + { + "id": "context7Key", + "label": "🔑 Context7 API key", + "type": "userInput", + "regex": "^(skip|[A-Za-z0-9._-]{8,})$", + "errorMessage": "Enter a Context7 API key (at least 8 characters: letters, digits, '.', '_' or '-'), or keep skip.", + "placeholder": "ctx7sk-...", + "default": "skip" + } + ], + "command": { + "windows": "& ([scriptblock]::Create((iwr -useb https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.ps1).Content)) mcp -ContentRef \"${guidelinesBranch}\" -Servers \"${mcpServers}\" -Agents \"${mcpAgents}\" -Scope \"${mcpScope}\" -Context7Key \"${context7Key}\"", + "macos": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- mcp --content-ref \"${guidelinesBranch}\" --servers \"${mcpServers}\" --agents \"${mcpAgents}\" --scope \"${mcpScope}\" --context7-key \"${context7Key}\"", + "linux": "set -o pipefail; curl -fsSL https://raw.githubusercontent.com/jmix-framework/jmix-agent-toolkit/${guidelinesBranch}/install.sh | bash -s -- mcp --content-ref \"${guidelinesBranch}\" --servers \"${mcpServers}\" --agents \"${mcpAgents}\" --scope \"${mcpScope}\" --context7-key \"${context7Key}\"" + } + } + ] + } +}