Skip to content
Merged
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
270 changes: 166 additions & 104 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,149 +1,211 @@
# LastState CLI

> **v1.2.0.** Scaffold + build + flash + test + mock + ingest + analyze + symbolicate + stack (`up/down/ps/logs/status/sim/deploy/doctor`) + brand logo in every banner.
> `test` is honest: anything it cannot verify prints `-`, never a false pass. Real validation via `protocol/test-vectors/` and `latch/hil/`.
One command line for the Latch → LEP → Relay → Trace loop: scaffold the Latch
integration, build and flash firmware, run the stack locally, and decode
captured envelopes.

## Installation
[![CI workflow status on master](https://github.com/laststate/cli/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/laststate/cli/actions/workflows/ci.yml)
[![Licensed under Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
[![Requires Node 18 or newer](https://img.shields.io/badge/node-18%2B-339933.svg)](package.json)

Requires Node 18+:
> **Status:** `v1.2.0`, CI green on `master`. The first tagged release is
> pending; until it ships, install from source. Hardware evidence lives in the
> [Latch repository](https://github.com/laststate/latch).

```bash
npm install -g laststate-cli
laststate --help
## What it does

- **Firmware:** `init` scaffolds the Latch integration files for ESP32,
Cortex-M, RISC-V, Zephyr, Arduino or host; `build` drives CMake and `ctest`;
`flash` calls `idf.py`, `west` or OpenOCD.
- **Stack:** `up` starts the LastState compose stack, `sim` runs a virtual
fleet, and `mock` serves Trace/Relay endpoints without Docker.
- **Evidence:** `test` checks the integration against LEP vectors; `ingest`,
`analyze` and `symbolicate` move and decode captures.
- **Operations:** `config` and `doctor` keep endpoints, secrets and toolchains
honest.

The CLI is glue: it drives the component repos' public commands and APIs, and
prints `-` when it cannot verify something.

## Install

Node 18+.

### From source (works today)

```sh
git clone https://github.com/laststate/cli.git
cd cli
npm ci
npm run build
npm link # exposes `laststate` and `ls`
laststate doctor
```

Global flags on **every** command:
### From npm (pending first release)

```text
--json --yes --verbose --quiet --no-color --no-banner --profile <name>
```sh
# 404 until the first tagged release is published
npm install -g laststate-cli
```

`--json` disables colors/banners/spinners and emits machine-readable JSON. `CI=true` also disables the banner.
The package is not on the registry yet; the first tagged release will publish
it. Until then, use the source install above.

## Quickstart

## Brand / logo
`laststate` is a driver, not a project generator: it runs against your firmware
checkout and the [LastState stack](https://github.com/laststate/laststate).

No animation, no images: every banner shows the **ASCII logo** (truecolor Braille generated from the real pixels of `cli/assets/brand.png` — swoosh, slashes and wordmark). Brand-tone spinners and `◆` as the success mark:
### Check the environment

```bash
laststate brand # ASCII logo
laststate brand --json # brand metadata for scripts
```sh
laststate doctor
```

`doctor` reports tools, config, secrets and live endpoints. It prints `-` for
anything it cannot check (a stack that is not running, for example) and exits
nonzero only when a required check fails.

### Run the stack

```sh
git clone --recurse-submodules https://github.com/laststate/laststate.git
cd laststate
laststate up --open
laststate sim run --scenario crash-storm
laststate status
laststate down
```

To regenerate the PNG from the vector: `assets/brand-source.html` + headless Edge screenshot at 2176×266.
`up` runs `docker compose` from the repo root, waits for health and can open
the Trace UI. `--appliance` uses `docker-compose.appliance.yml`; `--no-sim`
skips the simulator. `sim run` accepts `demo`, `steady`, `crash-storm`,
`outage`, `recovery` or `boot-loop`.

## Quickstart (4 min)
### Add Latch to firmware

```bash
```sh
laststate init --project-name Demo --target cortex-m --yes
cd Demo
laststate build --preset host-debug # cmake presets + ctest
laststate mock --port 8080 & # mock Trace/Relay
laststate test --verbose # probes + LEP vectors
laststate ingest crash.lep --to relay --url http://localhost:8384
laststate analyze crash.lep
```

Firmware (`main.c` generated):

```c
#include <latch/latch.h>

void app_init(void) {
static ls_config_t cfg = {
.device_id = "demo-001",
.firmware_version = "v1.0.0",
.build_id = "dev-build",
};
ls_init(&cfg);
/* ls_transport_register(uart_transport); -- before ls_boot() */
ls_boot();
ls_breadcrumb("app:init");
}
`init` creates `Demo/` with `laststate.yaml`, a Latch `main.c`, `.gitignore`
and `CMakeLists.patch.txt` (plus `partition.csv` for ESP32). It does **not**
create a buildable project: merge the patch into your own `CMakeLists.txt`,
add Latch under `third_party/latch`, and provide the CMake preset that
`build` will use. Latch's own `CMakePresets.json` is the reference for
`host-debug`, `arm-cortex-m4`, `riscv32` and `riscv64`.

With those in place, `laststate build`, `laststate flash` and
`laststate test` run against your project. `test` probes includes,
`ls_boot()` wiring and the LEP vectors it can find; anything it cannot
verify prints `-`, never a false pass.

The generated `laststate.yaml` carries a local-only `dev-` ingest token.
Replace it before sharing the project or pointing it at a shared Relay;
`laststate config generate-secrets` writes strong values to `.env`, which take
precedence over the project file.

## Inspect a capture

```sh
laststate analyze capture.lep
laststate analyze capture.lep --output-format json
laststate ingest capture.lep --to relay --url http://localhost:8384
```

## Commands
`analyze` accepts `.lep`, `.hex` and `.bin`, checks the header and CRCs, walks
TLVs and can deframe `raw`, `latch-stream` or `cobs`. A protocol vector works
as a known-good input:
`laststate analyze ../protocol/test-vectors/valid/lep-v2-basic.hex`.

`ingest` posts to Relay or Trace with a rate/ETA bar and reports the event ID.
`symbolicate upload-artifact` stores an ELF in Trace; `symbolicate resolve`
uses `llvm-symbolizer` or `addr2line` locally.

## Common commands

### Project / firmware
### Firmware

| Command | What it does |
|---|---|
| `laststate init [--project-name --target esp32\|cortex-m\|riscv\|riscv64\|zephyr\|arduino\|host --lep 1\|2 --storage --relay-url --trace-url --no-git --yes]` | Wizard (clack) + scaffold `laststate.yaml`, `main.c` (correct `ls_config_t` API), `CMakeLists.patch.txt`, `partition.csv` for ESP32, best-effort `git init` |
| `laststate build [--preset --clean --jobs]` | `cmake --preset + --build + ctest` as a live checklist, preset suggested from `target` |
| `laststate flash [--port --baud --no-monitor]` | `idf.py flash` (esp32) / `west flash` (zephyr) / `openocd` (cortex-m), confirms port |
| `laststate test [--verbose --filter --vectors-path]` | `✓/✗/-`: yaml schema, latch includes, `transport_register`+`ls_boot` grep, `protocol/test-vectors` (valid must pass, invalid must reject), spool/HIL as `-` |
| `laststate ingest|send [file\|dir] [--to relay\|trace --url --token]` | `POST octet-stream` with rate/ETA bar, `201/200+X-Event-ID` (relay) / `202` (trace), dev-token warning |
| `laststate analyze <file\|dir> [--output-format json\|text]` | 24B header, `header_crc`+`payload_crc` (CRC32), TLVs `1..22/0x20/0x30/0x8000`, deframing `raw|latch-stream|cobs|len-prefix`, accepts `.hex` |
| `laststate symbolicate upload-artifact <elf> / resolve <addr...> --elf <elf>` | `POST /v1/artifacts` or local `llvm-symbolizer/addr2line` (checks `build_id`) |
| --- | --- |
| `laststate init` | Scaffold Latch integration files for `esp32`, `cortex-m`, `riscv`, `riscv64`, `zephyr`, `arduino` or `host`. |
| `laststate build` | Configure and build with CMake presets, then run `ctest`. |
| `laststate flash` | Flash through `idf.py`, `west` or OpenOCD. |
| `laststate test` | Static integration probes plus LEP vectors; `✓`/`✗`/`-` per check. |

### Mock / stack / deploy
### Stack

| Command | What it does |
|---|---|
| `laststate mock [--port --host --require-auth --token --no-cors]` | Mirrors the real thing: `POST /v1/ingest→201/200`, `POST /v1/events→202`, `POST /v1/events:batch`, `GET /v1/{ingest,relay}/capabilities`, `/health/live\|ready`, `/metrics`, optional Bearer |
| `laststate up [--appliance --build --no-sim --services a,b --wait-timeout --open]` | `docker compose up -d` as a live checklist, Trace+Relay health-wait, URL table |
| `laststate down [--appliance --volumes]` / `ps` / `logs [svc] [--follow --tail]` / `status [--url]` | Manages and audits the stack |
| `laststate sim run [--scenario demo\|steady\|crash-storm\|outage\|recovery\|boot-loop --rate --devices --duration]` / `sim stop` | Brings up the `simulator` service with `SIM_*` |
| `laststate deploy --env local\|production\|appliance\|k8s` | `generate-secrets --only-missing` + `preflight` gate (prod) + `compose up --build`; k8s prints a hint |
| `laststate config list\|get\|set\|paths\|generate-secrets\|preflight` | Real YAML + masked `.env` + global `conf`; never logs a literal secret |
| `laststate doctor [--fix]` | Tools (git/docker/cmake/node), `laststate.yaml`, `.env`, `relay-config.yaml` (`env:` refs, no literals), preflight, live endpoints |
| `laststate update` | Checks `npm view laststate-cli version` |
| `laststate brand` | ASCII logo (braille dots) / `--json` metadata |

### Config

```bash
laststate config list
laststate config get trace_url
laststate config set trace_url http://localhost:8080
laststate config generate-secrets --only-missing
laststate config preflight --deploy-env production
laststate config paths
```
| --- | --- |
| `laststate up` / `down` / `ps` / `logs` / `status` | Start, stop, list, tail or health-check the compose stack. |
| `laststate sim run` / `sim stop` | Run the virtual fleet with a named scenario. |
| `laststate deploy` | Secrets, preflight and `compose up` for `local`, `production`, `appliance` or `k8s`. |
| `laststate doctor` | Audit tools, config, secrets and live endpoints. |
| `laststate mock` | Serve Trace/Relay endpoints for development without Docker. |

Precedence: `--flag > env (TRACE_URL, LASTSTATE_*_TOKEN) > laststate.yaml > global conf > default`.
### Captures and config

## Examples
| Command | What it does |
| --- | --- |
| `laststate ingest` (alias `send`) | POST `.lep` files to Relay or Trace. |
| `laststate analyze` | Decode header, CRCs, TLVs and framing; text or JSON. |
| `laststate symbolicate` | `upload-artifact` to Trace or `resolve` addresses locally. |
| `laststate config` | `list`, `get`, `set`, `paths`, `generate-secrets`, `preflight`. |
| `laststate billing` | `status`, `checkout`, `portal`, `watch` against billing-service. |
| `laststate update` | Check for a newer CLI version. |

```bash
# interactive init per target
laststate init --target esp32
Per-command flags: `laststate <command> --help`. Global flags on every command:

# vectors only + json for CI
laststate test --json --verbose
```text
--json --yes --verbose --quiet --no-color --no-banner --profile <name>
```

# whole directory analyze in json
laststate analyze ./captures --output-format json
`--json` disables colors, banners and spinners and emits machine-readable
output. `CI=true` also disables the banner.

# batch ingest to prod trace
laststate ingest ./captures --to trace --url https://trace.example.com --token $LASTSTATE_COMPANY_TOKEN
## Configuration

# appliance stack without sim
laststate up --appliance --build
laststate ps && laststate status
laststate logs relay --tail 50
laststate down
Precedence: `--flag > env > laststate.yaml > global conf > default`. Common
environment names are `TRACE_URL`, `RELAY_URL` and `LASTSTATE_*_TOKEN`.

# prod deploy (fails on REPLACE_ME/weak)
laststate deploy --env production
```sh
laststate config list
laststate config get trace_url
laststate config set trace_url http://localhost:8080
laststate config generate-secrets --only-missing
laststate config preflight --deploy-env production
laststate config paths
```

## Experience (animations)

- **Live checklist** in `init`, `build`, `up`, `deploy`: each step goes `○ → ◜ → ✓/✗` with duration; failures print the error and abort as before.
- **Spinners with duration**: every `withSpinner` ends in `◆ <step> · 3.1s`; `up` shows URL + elapsed seconds during the health-check.
- **Bars with rate and ETA**: `ingest` shows `files/s`, KB sent and ETA; same base in `build`.
- **Wizard with `@clack/prompts`**: `init` (name + target), `flash` (port + confirmation), `sim` (scenario), `deploy` (env), `ingest` (file) — arrows, defaults and clean `Ctrl+C` ("Cancelled.", exit 1).
- **Closing line**: `◆ <command> … · done in Xs` at the end of `init`, `build`, `up`, `deploy`.
- General rule: everything turns off with `--json` / `--quiet` / `--no-banner` / `CI=true` / no TTY (checklist becomes static lines, bars become noops).
`config generate-secrets` fills only missing or weak values. `config preflight`
fails on `REPLACE_ME` placeholders and weak secrets before a production deploy.

## Tests
## Development

```bash
npm test # vitest: lep, env-manager, validate, wiring, tasks, ui (40 tests)
npm run build # tsc → dist/
```sh
npm ci
npm test # vitest: LEP codec, config, validation, wiring, tasks, UI
npm run build # tsc -> dist/
npm run lint
```

To release, push a `vX.Y.Z` tag equal to `package.json`. The release workflow
builds and tests, publishes to npm (OIDC trusted publishing or `NPM_TOKEN`),
packs the tarball, smoke-tests the published package and creates the GitHub
release.

## Documentation

Full docs: https://docs.laststate.io — quickstarts in `docs/quickstarts/`, HIL in `latch/hil/`, vectors in `protocol/test-vectors/`.
| Topic | Where |
| --- | --- |
| Latch runtime and HIL evidence | [laststate/latch](https://github.com/laststate/latch) |
| LEP wire format and vectors | [laststate/protocol](https://github.com/laststate/protocol) |
| Relay gateway | [laststate/relay](https://github.com/laststate/relay) |
| Trace backend and UI | [laststate/trace](https://github.com/laststate/trace) |
| Full self-hosted stack | [laststate/laststate](https://github.com/laststate/laststate) |
| Billing realtime contract | [docs/BILLING_REALTIME.md](docs/BILLING_REALTIME.md) |

## License

Apache-2.0. See [LICENSE](LICENSE).
4 changes: 2 additions & 2 deletions src/commands/ingest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export async function ingest(input: string | undefined, rawOpts: IngestOpts) {
}

const endpoint = to === "trace" ? `${url.replace(/\/$/, "")}/v1/ingest` : `${url.replace(/\/$/, "")}/v1/ingest`;
const bar = progressBar(files.length, "ingest", "arq");
const bar = progressBar(files.length, "ingest", "file");
const results: Array<{ file: string; id?: string; status?: number; duplicate?: boolean; error?: string }> = [];
let sentBytes = 0;
for (const f of files) {
Expand All @@ -81,7 +81,7 @@ export async function ingest(input: string | undefined, rawOpts: IngestOpts) {
});
const body = await res.text().catch(() => "");
let parsed: { id?: string; duplicate?: boolean } = {};
try { parsed = JSON.parse(body); } catch { /* noop */ }
try { parsed = JSON.parse(body); } catch { /* ignore */ }
const id = res.headers.get("X-Last-State-Event-ID") ?? parsed.id;
results.push({ file: basename(f), id: id ?? undefined, status: res.status, duplicate: parsed.duplicate });
if (![200, 201, 202].includes(res.status)) {
Expand Down
Loading