* docs: add an exit-code table and generated --help snapshots README gains the exit codes scripts can rely on, per command. docs/help holds the --help text of every command in every tree, and HelpSnapshotTest fails when the files and the commands drift apart. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * docs: say which rejected values exit 1 and pin the documented exit codes with a test The table promised 2 for every unusable value, but three commands report a rejected value with 1. The wording is narrowed, the three are named, and ExitCodeTableTest pins the rows that need neither Docker nor a server. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * test: keep the exit-code test off the developer's saved profiles The profile commands build their own store under the home directory, so the test now runs with a temporary home. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com>
17 KiB
AGENTS.md
Guidance for AI coding agents working in the floci-cli repository.
This file defines repository-specific operating rules for autonomous or semi-autonomous coding agents. Follow these instructions unless a maintainer explicitly tells you otherwise.
Project Overview
floci-cli is the official command-line interface for Floci, the free, open-source local cloud emulator for AWS, GCP, and Azure. It manages emulator lifecycle (start/stop/status/logs), configuration profiles, diagnostics (doctor), and state snapshots.
- Stack: Java 25, Picocli 4.7.x, Jackson (JSON + YAML), JUnit 5
- Distribution: GraalVM native binaries (linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64) + fat-JAR fallback
- No frameworks beyond Picocli: plain
java.net.http.HttpClientanddockerCLI subprocesses
Build and Test Commands
mvn compile # compile only
mvn test # run all unit tests
mvn test -Dtest=WaitCommandParseTest # run a single test class
mvn test -Dtest=DockerVersionCheckTest#testVersionParsing # run a single test method
mvn test -Pintegration # integration suite: the CLI against real emulator images (needs Docker)
mvn package # compile + test + produce target/floci.jar (fat JAR)
mvn package -DskipTests # skip tests
mvn package -Pnative -DskipTests # build native binary → target/floci (requires GraalVM)
Running the fat JAR (requires Java 25+):
java -jar target/floci.jar <command>
Architecture
Entry point and command wiring
FlociCli is the Picocli root command. Every subcommand is registered in its subcommands = {} array. All commands implement Callable<Integer> and return an exit code.
Bare commands (floci start) route to the configured default product (aws unless changed via floci config default-product aws|gcp|az|oci). Explicit product groups are floci aws (same classes as the root tree), floci gcp, floci az, and floci oci.
The unified product tree (CRITICAL)
There is ONE implementation of every shared command, in commands/, parameterized by ProductProfile (io.floci.cli.ProductProfile), the single source of per-product config:
| Profile | Default endpoint | Container | Env prefix | Control prefix |
|---|---|---|---|---|
AWS (root tree) |
http://localhost:4566 |
floci |
FLOCI_* |
/_floci |
GCP |
http://localhost:4588 |
floci-gcp |
FLOCI_GCP_* |
/_floci-gcp |
AZ |
http://localhost:4577 |
floci-az |
FLOCI_AZ_* |
/_floci (same as AWS, intentional) |
OCI |
http://localhost:4599 |
floci-oci |
FLOCI_OCI_* |
/_floci-oci |
The commands/gcp/, commands/az/, and commands/oci/ leaf classes are ~8-line shims: GcpStartCommand extends StartCommand { super(ProductProfile.GCP); } with their own @Command annotation carrying the per-product description. ProductProfileTest pins every profile field; ProductTreesParsingTest pins each tree's defaults.
Rules for the unified tree:
- Every parameterized command pre-initializes its mixin in the constructor:
this.global = new GlobalOptions(profile). Picocli uses a non-null@Mixinfield instance as-is; a command that forgets gets AWS defaults in every tree (the per-tree parse tests catch this). - Per-product option defaults are constructor-set field values, not annotation
defaultValues (annotation strings are compile-time constants). Use(default: ${DEFAULT-VALUE})in the option description to render them in help. - Never subclass a group command (
GcpCommand,*ConfigCommand,*SnapshotCommandgroups): picocli registers thesubcommandsarrays of both super and subclass, an instant duplicate-name crash. Groups stay standalone registration-only classes. - Product-varying strings come from the profile:
displayName()for banners,commandPrefix()for hint strings,envVar("SERVICES")for container env vars,controlPrefix()forFlociHttpClient,serverRepo()for issue-tracker links. - Only
EnvCommand/GcpEnvCommand/AzEnvCommand/OciEnvCommandare genuinely product-specific (not shims), plus two product-onlysetupcommands:OciSetupCommand(the OCI CLI/SDKs require a config file + signing key, sofloci oci setupscaffolds them) andAzSetupCommand(theazCLI needs a registered cloud, the emulator's CA trusted and a login, sofloci az setupdoes that throughio.floci.cli.azcli). AWS and GCP need no equivalent.add-command/checklist.sh setupreports the shared-tree rows as MISSING for these by design.
Commands call global.printer() at the start of call(); never store a Printer as a field.
Two I/O boundaries
Docker: DockerClient wraps docker CLI subprocesses, with no docker-java library. This is a deliberate native-image trade-off. DockerClient returns plain records (ContainerInfo, ImageInfo) and throws DockerException on non-zero exit codes.
Floci server: FlociHttpClient wraps java.net.http.HttpClient against the Floci REST API. All methods throw FlociException. The control-plane prefix is constructor-configurable: AWS and Azure use /_floci, GCP uses /_floci-gcp. Known live endpoints: /_floci/health, /_floci/info, /_floci/init, POST <prefix>/state/reset (AWS, GCP and OCI; floci reset), and on floci-az only /_floci/tls-cert (tlsCert(), the PEM CA; 404 when TLS is off). Snapshot endpoints (/_floci/snapshots/*) do not exist on the server yet.
Output pipeline
Every command checks printer.format() to decide between text and structured output:
if (printer.format() != OutputFormat.text) {
printer.structured(map); // renders as JSON or YAML via Jackson
return 0;
}
// ... build human-readable text with Ansi helpers
Ansi is a static utility with a global disable() call (triggered by --no-color or non-TTY). Color is disabled once per JVM invocation; it cannot be re-enabled.
Doctor checks
Check is a @FunctionalInterface taking (endpoint, container) and returning CheckResult. Order matters: Docker checks run before server checks because later checks depend on Docker being up.
One DoctorCommand serves every tree: dockerChecks(profile) builds the 9 Docker/server checks (image and control prefix from the profile), and the constructor appends the product's companion list: AWS_COMPANION_CHECKS (AWS CLI checks), AZ_COMPANION_CHECKS (az CLI checks), empty for GCP/OCI. DoctorCheckListTest pins each product's composition and order.
To add a check: create a class in doctor/checks/, then add it to dockerChecks() (all products) or the relevant companion list.
Config profiles
ProfileStore reads/writes YAML files under ~/.floci/profiles/<name>.yaml via Jackson. Profile is a plain bean; keep it @JsonIgnoreProperties(ignoreUnknown = true) to stay forward-compatible. The store is shared by all four product trees (no per-product namespacing). GlobalConfigStore persists ~/.floci/config.yaml (currently just default-product).
--profile is applied by exactly one class; do not add per-command profile reads. ProfileDefaultValueProvider is a picocli IDefaultValueProvider registered once in FlociCli.buildCommandLine(...); picocli propagates it to the whole subcommand tree and consults it only for options the user did not pass, after that command's arguments have been processed. That yields the documented precedence for free:
command-line flag > --profile <name> > FLOCI_* env var > product default
(the env var and product default are the GlobalOptions field initial values, which picocli keeps whenever the provider returns null).
Rules when touching this:
- The field→flag mapping lives in
ProfileDefaults.valueForas a pure function, matched on exact option names.--service(wait/logs/env) is not--services;--profile-name(floci oci setup) is not--profile. - The provider is called for positionals and for commands with no
GlobalOptionsmixin (update, the group commands, the root); both guards must stay. - Register it programmatically. The annotation form
@Command(defaultValueProvider = ...)makes picocli instantiate it reflectively and would need areflect-config.jsonentry. - A bad profile throws
ProfileNotFoundException(aParameterException), whichFlociCli's parameter-exception handler renders without a usage dump and exits 2. The provider returnsnullwhen-h/-Vwas requested so--helpstill works. - A command that reads the profile back after parsing (
RestartCommandbuilding itsStartCommand,ConfigShowCommand) gets the parse's provider withProfileDefaultValueProvider.of(spec)(an@Spec CommandSpec specfield) and passes it toStartCommand.resolvedFor. The provider memoizes the profile it resolved, so this reuses the parse's snapshot; never construct aProfileStoreor a second provider in a command. - Use
FlociCli.buildCommandLine(ProfileStore)in tests;new CommandLine(new FlociCli())has none of the wiring.
Multiple instances
An instance is a profile: its container name is its identity, its port is the only thing that must differ, and its persist dir keeps its state. Rules:
- Commands find their instance through the container (
GlobalOptions.resolvedEndpoint); never persist an endpoint as instance identity. - Local state about one running instance (certificates, generated vendor-CLI config) lives under
InstanceState.dir(product, container), which is~/.floci/<product>/<container>/. Never a fixed per-product path: a second instance would overwrite the first.floci az setupis the reference (its az cloud is also named after the container). - Hints that tell the user to re-run a command append
global.instanceSelector()so they select the same instance again. - Instance-independent state (the OCI CLI profile from
floci oci setup) may stay shared. StartCommand.resourceNamespace()passes the emulator's<PREFIX>_DOCKER_RESOURCE_NAMESPACE: explicit--namespace/profilenamespace(verbatim), elseProductProfile.resourceNamespace(container): nothing for the default container, otherwise the container name minus the<defaultContainer>-prefix (the emulator addsfloci-<cloud>-itself, so keeping it would stutter). It scopes the child containers each emulator launches and its orphan sweeps; never derive one for the default container (it would rename existing users' child containers).- On a non-default
--port,startalso passes<PREFIX>_BASE_URL, the endpoint with that port (http://localhost:<port>by default): every emulator builds returned URLs (SQSQueueUrl, OCI invoke endpoint) from it, and its default names the product port. config profile createtakes--container --port --persist --services --image --namespace(and--endpoint); it reads only flags the user typed (ParseResult.hasMatchedOption), never values the profile provider orFLOCI_*env vars applied.
Self-update
UpdateCommand (floci update) downloads the release binary for the current platform, verifies its sha256 against the release's sha256sums.txt, and atomically replaces the running binary (staged in the same directory, ATOMIC_MOVE). It refuses to update Homebrew-managed installs. --check exits 0 when up to date, 1 when an update is available. ReleaseChannel builds the GitHub release asset URLs.
Code Style and Good Practices
- Prefer
recordfor data carriers. Any DTO, value object, or result type that just holds data should be arecord(likeContainerInfo,ImageInfo,CheckResult,HealthInfo), not a mutable bean with getters/setters. Exception: Jackson-mapped config beans that must stay forward-compatible and field-name-bound for the native image (Profile,GlobalConfig) may stay as plain beans; if you do make a Jackson-(de)serialized type a record, it still needs areflect-config.jsonentry. - Prefer constructor injection over field mutation. Collaborators (
DockerClient,FlociHttpClient,ProfileStore, check lists) should be passed through the constructor and stored infinalfields; seeDoctorCommand(List<Check> companionChecks)for the pattern. Provide a no-arg constructor with defaults for Picocli, and a parameterized one as the test seam. Exception: Picocli requires non-final fields for@Option,@Parameters, and@Mixin; that is framework-mandated and fine. - Import classes; don't fully-qualify inline. Add an
importand use the simple name instead of writingio.floci.cli.output.Printer(orjava.util.List, etc.) inline in signatures and bodies. Avoid wildcard imports except the existingpicocli.CommandLine.*convention. - Keep fields
finalwherever possible; prefer immutable collections (List.of,List.copyOf) over mutable ones exposed outside a method.
Native Image Constraints
- No new reflection-heavy dependencies. If adding a library, verify it works under
--no-fallback. - New Jackson DTOs (anything
ObjectMapperserializes/deserializes by field name) must be added tosrc/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json. Prefer passingMap/JsonNodetoprinter.structured(...); those need no registration. @Commandclasses do not need manual reflect-config entries:picocli-codegen(the annotation processor inpom.xml) generates them automatically at compile time.- Do not remove
--enable-url-protocols=http,httpsfromnative-image.properties;java.net.http.HttpClientrequires it. - The native profile builds with
-Os(about 17% smaller with GraalVM Community, about 35% with Oracle GraalVM, for about 10 ms more startup).ci.ymlfails the native job when the linux/arm64 binary exceedsNATIVE_SIZE_BUDGET_MB; raise the budget deliberately in the PR that needs the room, and say why.
Scope Rules
- No cloud resource commands. This CLI manages Floci itself (lifecycle, config, diagnostics, state). Resource operations belong to the vendor CLIs pointed at the emulator:
aws+AWS_ENDPOINT_URL,gcloud/SDK emulator-host vars,az+ connection string. - No telemetry, no TUI, no Floci Cloud commands.
- Self-update is in scope (
floci update), but it must never auto-run; updates happen only on explicit user invocation. - Snapshot commands: the AWS
save/load/list/deletecall/_floci/snapshots/*and degrade gracefully (404/501 → "not available");export/importand the entire GCP/Azure/OCI snapshot subtrees are stubs pending server-side endpoints infloci-io/floci,floci-io/floci-gcp,floci-io/floci-az, andfloci-io/floci-oci. Do not invent client-side snapshot behavior: the server API contract comes first.
Error Message Convention
Every printer.error(...) call must end with a suggested next step:
printer.error("Container 'floci' not found.\nRun 'floci start' to launch one.");
Documentation Rules
README.mddocuments all four product trees (AWS, GCP, Azure, OCI). If you add/change a command or flag, update the README in the same change.docs/help/holds the generated--helptext of every command, andHelpSnapshotTestfails when it no longer matches the code. After changing a command, flag or description, regenerate it withmvn test -Dtest=HelpSnapshotTest -Dfloci.help.update=trueand commit the result; never edit those files by hand.- The
Exit Codestable inREADME.mdis the contract scripts rely on. A change to what a command returns updates that table in the same change. - The README header (logo, tagline, badges, nav row), the
The Floci emulatorstable and the closing Testcontainers / Community / License / trademark footer follow the Floci family pattern, withfloci-io/testcontainers-floci's README as the reference. Keep them in step with it rather than restyling them here. CHANGELOG.mdis generated by semantic-release from Conventional Commit messages; never edit it by hand. Afeat,fixorperfsubject (or a breaking change) becomes a release note verbatim, so write those from the user's point of view: what was broken or what is new, not how it was implemented. The other accepted types (docs,chore,refactor,test,build,ci) pass CI but produce no release and no entry.changelog-guard.ymlfails any PR that touches the file; genuine corrections to history need thechangelog-editlabel.- No em or en dashes (U+2014, U+2013) in tracked Markdown or in issue and PR text: use a colon, semicolon, comma, parentheses or a new sentence instead.
CHANGELOG.mdis exempt (generated from commit subjects). CLAUDE.mdis gitignored (maintainer-local); this file (AGENTS.md) is the tracked source of truth for agent guidance. Update it here.