From fb161dddeb1d0c944a3c721442fed589bf288673 Mon Sep 17 00:00:00 2001 From: Ryan Min <73128364+kcrmin@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:30:44 +0900 Subject: [PATCH 1/3] fix(cli): answer --help and --version in json A lone option reached getFirst() on an empty command list and exited 70. Options without a command are now usage errors (exit 2). --- apps/idea2strategy-cli/README.md | 6 +++ apps/idea2strategy-cli/build.gradle.kts | 7 +++ .../idea2strategy/cli/Idea2StrategyCli.java | 48 +++++++++++++++++ .../cli/ExternalAiToolE2eTest.java | 24 +++++++++ .../cli/Idea2StrategyCliTest.java | 54 +++++++++++++++++++ 5 files changed, 139 insertions(+) diff --git a/apps/idea2strategy-cli/README.md b/apps/idea2strategy-cli/README.md index 37d7461b..9cd18073 100644 --- a/apps/idea2strategy-cli/README.md +++ b/apps/idea2strategy-cli/README.md @@ -33,6 +33,8 @@ $password | idea2strategy login --email user@example.com Supported commands: ```text +--help +--version tool-contract catalog elements catalog instruments [--symbol TICKER[,TICKER...]] @@ -100,6 +102,10 @@ server would re-read the document and apply a diff nobody reviewed against its c The CLI rejects arbitrary code, external-data access, direct orders, unapproved delegation scopes, and apply requests that omit the reviewed preview hash. +`--help` lists the commands and stable exit codes, and `--version` reports the version the archive was +built as; both answer in the same JSON envelope as every other command. An option with no command in front +of it is a usage error (exit code 2). + Every successful response is written to standard output as `{ "ok": true, "command": "...", "data": ... }`. Every error is written to standard error as `{ "ok": false, "command": "...", "error": ... }`. diff --git a/apps/idea2strategy-cli/build.gradle.kts b/apps/idea2strategy-cli/build.gradle.kts index 470c1ee7..bf1ecde4 100644 --- a/apps/idea2strategy-cli/build.gradle.kts +++ b/apps/idea2strategy-cli/build.gradle.kts @@ -29,10 +29,17 @@ application { mainClass = "com.idea2strategy.cli.Idea2StrategyCli" } +tasks.named("jar") { + manifest { + attributes("Implementation-Version" to project.version.toString()) + } +} + tasks.named("test") { dependsOn(tasks.named("installDist")) systemProperty( "idea2strategy.cli.installDir", layout.buildDirectory.dir("install/idea2strategy").get().asFile.absolutePath, ) + systemProperty("idea2strategy.cli.version", project.version.toString()) } diff --git a/apps/idea2strategy-cli/src/main/java/com/idea2strategy/cli/Idea2StrategyCli.java b/apps/idea2strategy-cli/src/main/java/com/idea2strategy/cli/Idea2StrategyCli.java index 65358737..2327fcbd 100644 --- a/apps/idea2strategy-cli/src/main/java/com/idea2strategy/cli/Idea2StrategyCli.java +++ b/apps/idea2strategy-cli/src/main/java/com/idea2strategy/cli/Idea2StrategyCli.java @@ -54,6 +54,14 @@ public final class Idea2StrategyCli { "competition.list", "competition.get", "competition.delete"); + private static final String HELP_OPTION = "--help"; + private static final String VERSION_OPTION = "--version"; + private static final List UNAUTHENTICATED_COMMANDS = List.of( + "tool-contract", + "login", + "operator.bootstrap", + "operator.credential-provision", + "operator.credential-reset"); private Idea2StrategyCli() {} @@ -85,6 +93,12 @@ static int run(String[] args, InputStream stdin, OutputStream stdout, OutputStre } private static JsonNode execute(Invocation invocation, InputStream stdin, Map environment) { + if (invocation.commandArguments().equals(List.of(HELP_OPTION))) { + return help(); + } + if (invocation.commandArguments().equals(List.of(VERSION_OPTION))) { + return version(); + } Arguments arguments = Arguments.parse(invocation.commandArguments()); if (arguments.positionals().equals(List.of("operator", "bootstrap"))) { return OperatorBootstrapCommand.execute(arguments, environment, stdin); @@ -156,6 +170,33 @@ private static JsonNode toolContract() { } } + /** + * Answers `--help` in the same JSON envelope as every other command, so a caller that only + * parses JSON is not handed prose. The command list is derived from the dispatch tables, and + * the exit codes come from the tool contract, so neither can drift from what actually runs. + */ + private static JsonNode help() { + ObjectNode help = JSON.createObjectNode().put("usage", + "idea2strategy [--base-url URL] [--backtest-base-url URL] [--config-dir DIR] [options]"); + ArrayNode commands = help.putArray("commands"); + UNAUTHENTICATED_COMMANDS.forEach(command -> commands.add(command.replace('.', ' '))); + AUTHENTICATED_COMMANDS.stream().sorted().forEach(command -> commands.add(command.replace('.', ' '))); + commands.add(HELP_OPTION); + commands.add(VERSION_OPTION); + help.putArray("contractCommand").add("tool-contract"); + help.set("exitCodes", toolContract().path("exitCodes")); + return help; + } + + /** + * Reports the version the archive was built as. A release build stamps it from the cli-vX.Y.Z + * tag into the jar manifest; classes run straight from a source tree carry no manifest. + */ + private static JsonNode version() { + String version = Idea2StrategyCli.class.getPackage().getImplementationVersion(); + return JSON.createObjectNode().put("version", version == null ? "unknown" : version); + } + /** * Signs in through the browser so nothing driving this CLI ever handles a password. * @@ -674,7 +715,14 @@ static Invocation parse(String[] raw, Map environment) { if (values.isEmpty()) { throw Arguments.usage("A command is required"); } + if (values.equals(List.of(HELP_OPTION)) || values.equals(List.of(VERSION_OPTION))) { + return new Invocation(baseUrl, backtestBaseUrl, Path.of(config), null, + List.copyOf(values), values.getFirst().substring(2)); + } List words = values.stream().takeWhile(value -> !value.startsWith("--")).toList(); + if (words.isEmpty()) { + throw Arguments.usage("A command is required before any option; run --help for usage"); + } int commandWordCount = switch (words.getFirst()) { case "login" -> 1; case "catalog" -> 2; diff --git a/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/ExternalAiToolE2eTest.java b/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/ExternalAiToolE2eTest.java index 5127bbac..8ca04d5e 100644 --- a/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/ExternalAiToolE2eTest.java +++ b/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/ExternalAiToolE2eTest.java @@ -66,6 +66,30 @@ void publishesMachineReadableToolContractWithoutCredentials() throws Exception { assertThat(requestCount).hasValue(0); } + /** + * The installed launcher, not just the classes, has to report the version the archive was + * built as: that is what someone checks after unzipping a release. + */ + @Test + void installedLauncherAnswersHelpAndReportsTheBuiltVersion() throws Exception { + ProcessResult version = invoke(false, "--version"); + + assertThat(version.exitCode()).isZero(); + assertThat(version.stderr()).isEmpty(); + JsonNode versionOutput = JSON.readTree(version.stdout()); + assertThat(versionOutput.path("command").asText()).isEqualTo("version"); + assertThat(versionOutput.path("data").path("version").asText()) + .isEqualTo(System.getProperty("idea2strategy.cli.version")); + + ProcessResult help = invoke(false, "--help"); + + assertThat(help.exitCode()).isZero(); + assertThat(help.stderr()).isEmpty(); + assertThat(JSON.readTree(help.stdout()).path("data").path("contractCommand")) + .extracting(JsonNode::asText).containsExactly("tool-contract"); + assertThat(requestCount).hasValue(0); + } + @Test void externalToolReviewsPreviewDiffBeforeApplyingExactHash() throws Exception { Path operations = operations("SET_VALUE"); diff --git a/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/Idea2StrategyCliTest.java b/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/Idea2StrategyCliTest.java index 40441e31..b1a4a8f1 100644 --- a/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/Idea2StrategyCliTest.java +++ b/apps/idea2strategy-cli/src/test/java/com/idea2strategy/cli/Idea2StrategyCliTest.java @@ -216,6 +216,60 @@ void unknownCommandIsAUsageErrorEvenBeforeLogin() throws Exception { assertThat(requestPath.get()).isNull(); } + @Test + void helpListsEveryDispatchedCommandAndTheContractExitCodes() throws Exception { + Result result = run("", "--base-url", baseUrl, "--config-dir", tempDir.toString(), "--help"); + + assertThat(result.exitCode()).isZero(); + assertThat(result.stderr()).isEmpty(); + JsonNode output = JSON.readTree(result.stdout()); + assertThat(output.path("ok").asBoolean()).isTrue(); + assertThat(output.path("command").asText()).isEqualTo("help"); + JsonNode help = output.path("data"); + assertThat(help.path("usage").asText()).startsWith("idea2strategy ").contains(""); + assertThat(help.path("commands")).extracting(JsonNode::asText) + .contains("tool-contract", "login", "operator bootstrap", "strategy list", + "strategy edit preview", "strategy edit apply", "competition delete", + "--help", "--version"); + assertThat(help.path("contractCommand")).extracting(JsonNode::asText).containsExactly("tool-contract"); + assertThat(help.path("exitCodes").path("2").asText()).isEqualTo("invalid-usage"); + assertThat(requestPath.get()).isNull(); + } + + @Test + void versionAnswersInTheJsonEnvelopeWithoutCredentials() throws Exception { + Result result = run("", "--config-dir", tempDir.toString(), "--version"); + + assertThat(result.exitCode()).isZero(); + assertThat(result.stderr()).isEmpty(); + JsonNode output = JSON.readTree(result.stdout()); + assertThat(output.path("ok").asBoolean()).isTrue(); + assertThat(output.path("command").asText()).isEqualTo("version"); + assertThat(output.path("data").path("version").asText()).isNotBlank(); + assertThat(requestPath.get()).isNull(); + } + + /** + * An option with no command in front of it used to reach `getFirst()` on an empty list and + * surface as INTERNAL_ERROR (70). It is a usage mistake and must say so with exit code 2. + */ + @Test + void optionsWithoutACommandAreAUsageErrorNotAnInternalFailure() throws Exception { + for (String[] args : new String[][] { + {"--yes"}, + {"--help", "strategy", "list"}, + {"--version", "--yes"}, + {"--limit", "5", "strategy", "list"}}) { + Result result = run("", args); + + assertThat(result.exitCode()).as(String.join(" ", args)).isEqualTo(2); + assertThat(result.stdout()).isEmpty(); + assertThat(JSON.readTree(result.stderr()).path("error").path("code").asText()) + .as(String.join(" ", args)).isEqualTo("USAGE_ERROR"); + } + assertThat(requestPath.get()).isNull(); + } + @Test void requiredWorkflowCommandsUseVersionedApiRoutes() throws Exception { Files.writeString(tempDir.resolve("credentials.json"), "{\"sessionToken\":\"stored-token\"}"); From 3e0fc1d567fbd9108f60fb13ed57cc4505a7923e Mon Sep 17 00:00:00 2001 From: Ryan Min <73128364+kcrmin@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:31:43 +0900 Subject: [PATCH 2/3] ci(release): name only the archive in its checksum The .sha256 held the runner path, so the documented sha256sum -c failed next to the downloaded archive. --- .github/workflows/cli-release.yml | 6 ++++-- apps/idea2strategy-cli/README.md | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml index 4f4e3f7e..82773f6f 100644 --- a/.github/workflows/cli-release.yml +++ b/.github/workflows/cli-release.yml @@ -61,10 +61,12 @@ jobs: run: | set -euo pipefail archive="$(ls apps/idea2strategy-cli/build/distributions/*.zip)" - sha256sum "$archive" > "${archive}.sha256" + # Hash from inside the directory so the line names the file alone and + # `sha256sum -c` works wherever the two downloads land. + (cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")" > "$(basename "$archive").sha256") gh release view "$TAG" --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1 \ || gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ --title "Idea2Strategy CLI $TAG" \ - --notes "Requires Java 21. Verify with the published .sha256, unzip, and run \`bin/idea2strategy tool-contract\`." + --notes "Requires Java 21. Verify with \`sha256sum -c\` on the published .sha256, unzip, and run \`bin/idea2strategy tool-contract\`." gh release upload "$TAG" "$archive" "${archive}.sha256" \ --repo "$GITHUB_REPOSITORY" --clobber diff --git a/apps/idea2strategy-cli/README.md b/apps/idea2strategy-cli/README.md index 9cd18073..68992698 100644 --- a/apps/idea2strategy-cli/README.md +++ b/apps/idea2strategy-cli/README.md @@ -5,9 +5,11 @@ external-data fetching, or direct-order commands. ## Install -Download `idea2strategy-.zip` from a `cli-v*` release, verify it against the published -`.sha256`, and unzip it. The launcher is `bin/idea2strategy` (`bin/idea2strategy.bat` on Windows); -put its directory on `PATH`. **Java 21 must already be installed** — the archive carries no runtime. +Download `idea2strategy-.zip` and its `.sha256` from a `cli-v*` release, verify the archive +from the directory holding both with `sha256sum -c idea2strategy-.zip.sha256` (on macOS, +`shasum -a 256 -c idea2strategy-.zip.sha256`), and unzip it. The launcher is +`bin/idea2strategy` (`bin/idea2strategy.bat` on Windows); put its directory on `PATH`. **Java 21 must +already be installed** — the archive carries no runtime. An external AI tool should run `idea2strategy tool-contract` first and follow the JSON it returns rather than this file: the contract is what the released binary actually enforces. From a99759ea7c5f75c06838e851e68b405e243054d3 Mon Sep 17 00:00:00 2001 From: Ryan Min <73128364+kcrmin@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:32:43 +0900 Subject: [PATCH 3/3] ci(release): version the cli archive from its tag A cli-vX.Y.Z tag now builds idea2strategy-X.Y.Z.zip, and --version reports X.Y.Z, instead of every release shipping 0.1.0-SNAPSHOT. --- .github/workflows/cli-release.yml | 18 ++++++++++++++++-- apps/idea2strategy-cli/README.md | 3 ++- apps/idea2strategy-cli/build.gradle.kts | 4 ++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml index 82773f6f..fde90bf9 100644 --- a/.github/workflows/cli-release.yml +++ b/.github/workflows/cli-release.yml @@ -43,6 +43,19 @@ jobs: with: cache-read-only: true + # The archive is named and stamped with the version in the tag, so what a person + # downloads, and what `idea2strategy --version` reports, match the release. + - name: Derive the CLI version from the tag + env: + TAG: ${{ github.event.inputs.tag || github.ref_name }} + run: | + set -euo pipefail + if [[ ! "$TAG" =~ ^cli-v([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?)$ ]]; then + echo "::error::$TAG is not a cli-vX.Y.Z tag" + exit 1 + fi + echo "CLI_VERSION=${BASH_REMATCH[1]}" >> "$GITHUB_ENV" + # The tool contract is what an external AI reads before it does anything. A release # whose contract does not parse is worse than no release, so it is checked here and # not only in the unit tests that build it. @@ -50,7 +63,7 @@ jobs: run: | chmod +x gradlew ./gradlew :apps:idea2strategy-cli:test :apps:idea2strategy-cli:distZip \ - --no-daemon --build-cache + -PcliVersion="$CLI_VERSION" --no-daemon --build-cache jq -e '.contractCommand and .workflow and .exitCodes' \ apps/idea2strategy-cli/src/main/resources/idea2strategy-ai-tool-contract.json > /dev/null @@ -60,7 +73,8 @@ jobs: TAG: ${{ github.event.inputs.tag || github.ref_name }} run: | set -euo pipefail - archive="$(ls apps/idea2strategy-cli/build/distributions/*.zip)" + archive="apps/idea2strategy-cli/build/distributions/idea2strategy-${CLI_VERSION}.zip" + test -f "$archive" # Hash from inside the directory so the line names the file alone and # `sha256sum -c` works wherever the two downloads land. (cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")" > "$(basename "$archive").sha256") diff --git a/apps/idea2strategy-cli/README.md b/apps/idea2strategy-cli/README.md index 68992698..6052f661 100644 --- a/apps/idea2strategy-cli/README.md +++ b/apps/idea2strategy-cli/README.md @@ -9,7 +9,8 @@ Download `idea2strategy-.zip` and its `.sha256` from a `cli-v*` release from the directory holding both with `sha256sum -c idea2strategy-.zip.sha256` (on macOS, `shasum -a 256 -c idea2strategy-.zip.sha256`), and unzip it. The launcher is `bin/idea2strategy` (`bin/idea2strategy.bat` on Windows); put its directory on `PATH`. **Java 21 must -already be installed** — the archive carries no runtime. +already be installed** — the archive carries no runtime. A `cli-vX.Y.Z` release ships +`idea2strategy-X.Y.Z.zip`, and `idea2strategy --version` reports `X.Y.Z`. An external AI tool should run `idea2strategy tool-contract` first and follow the JSON it returns rather than this file: the contract is what the released binary actually enforces. diff --git a/apps/idea2strategy-cli/build.gradle.kts b/apps/idea2strategy-cli/build.gradle.kts index bf1ecde4..702b9049 100644 --- a/apps/idea2strategy-cli/build.gradle.kts +++ b/apps/idea2strategy-cli/build.gradle.kts @@ -24,6 +24,10 @@ sourceSets { test { resources.srcDir(project(":db-migration").file("src/main/resources")) } } +// A cli-vX.Y.Z release passes -PcliVersion=X.Y.Z, so the archive name and the version that +// `idea2strategy --version` reports come from the tag rather than the build-wide default. +providers.gradleProperty("cliVersion").orNull?.let { version = it } + application { applicationName = "idea2strategy" mainClass = "com.idea2strategy.cli.Idea2StrategyCli"