Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions .github/workflows/cli-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,27 @@ 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.
- name: Build and verify the distribution
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

Expand All @@ -60,11 +73,14 @@ jobs:
TAG: ${{ github.event.inputs.tag || github.ref_name }}
run: |
set -euo pipefail
archive="$(ls apps/idea2strategy-cli/build/distributions/*.zip)"
sha256sum "$archive" > "${archive}.sha256"
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")
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
15 changes: 12 additions & 3 deletions apps/idea2strategy-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ external-data fetching, or direct-order commands.

## Install

Download `idea2strategy-<version>.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-<version>.zip` and its `.sha256` from a `cli-v*` release, verify the archive
from the directory holding both with `sha256sum -c idea2strategy-<version>.zip.sha256` (on macOS,
`shasum -a 256 -c idea2strategy-<version>.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. 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.
Expand All @@ -33,6 +36,8 @@ $password | idea2strategy login --email user@example.com
Supported commands:

```text
--help
--version
tool-contract
catalog elements
catalog instruments [--symbol TICKER[,TICKER...]]
Expand Down Expand Up @@ -100,6 +105,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": ... }`.

Expand Down
11 changes: 11 additions & 0 deletions apps/idea2strategy-cli/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,26 @@ 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"
}

tasks.named<Jar>("jar") {
manifest {
attributes("Implementation-Version" to project.version.toString())
}
}

tasks.named<Test>("test") {
dependsOn(tasks.named("installDist"))
systemProperty(
"idea2strategy.cli.installDir",
layout.buildDirectory.dir("install/idea2strategy").get().asFile.absolutePath,
)
systemProperty("idea2strategy.cli.version", project.version.toString())
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> UNAUTHENTICATED_COMMANDS = List.of(
"tool-contract",
"login",
"operator.bootstrap",
"operator.credential-provision",
"operator.credential-reset");

private Idea2StrategyCli() {}

Expand Down Expand Up @@ -85,6 +93,12 @@ static int run(String[] args, InputStream stdin, OutputStream stdout, OutputStre
}

private static JsonNode execute(Invocation invocation, InputStream stdin, Map<String, String> 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);
Expand Down Expand Up @@ -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] <command> [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.
*
Expand Down Expand Up @@ -674,7 +715,14 @@ static Invocation parse(String[] raw, Map<String, String> 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<String> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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("<command>");
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\"}");
Expand Down
Loading