Canonical page: [JSON API and Remote Access](https://cloudflavor.io/aemon/docs/json-api/)
Source snapshot: https://github.com/cloudflavor/aemon/blob/a85ee1d024b81c6373acd86379fe12f15c26a7a5/docs/json-api.md

# JSON API and Remote Access

Reporting commands emit a common envelope on stdout:

```json
{
  "cmd": "search",
  "db": "/path/to/aemon.db",
  "result": { "query": "connect", "hits": [] }
}
```

This changes the machine-readable format used by scripts, not how people type
normal commands. For example, a script that previously read a search's JSON array
now reads `response.result.hits`; `response.cmd` names the command and `response.db`
identifies the database that answered. The built-in remote client forwards this
output unchanged. No other production JSON-parsing consumers exist in this repo;
external integrations need their own compatibility check.

Human-readable output is unchanged apart from corrected freshness warnings and
explicit failure exit codes.

| Invocation | Fields under `result` |
| --- | --- |
| `search QUERY --json` | `query`, `hits` |
| `outline QUERY --json` | `query`, `hits` |
| `get ID --json` | entry metadata, `body`, `body_chars`, expansion/budget flags, `freshness` |
| `fresh TARGET --json` | `target`, `freshness`, `guidance` (or close `matches`) |
| `ls --json`, `stats --json` | `corpora`, including per-corpus freshness |
| `resolve QUERY --json` | `query`, `libraries` (or `plan` with `--auto`) |
| `models --json` | `models` (key presence only; never credentials) |
| `crawl status --json` | `sources`, including last status and age in hours |
| `audit --json` | `audit` |
| `sources --format json` | `recipes` |
| `serve --json` | `bind`, `jobs`, `read_only_commands`; exits without listening |

`sources --format json --out FILE` retains its existing bare manifest-file format.
Errors still appear on stderr; a failed command is not guaranteed to emit JSON.

## Routing and coverage

`search --auto --decider SPEC` and `outline --auto --decider SPEC` override the
configured routing-model role for that invocation. Existing named model specs and
provider specs work. An OpenAI-compatible example is
`--decider openai:http://127.0.0.1:8082/model-name`.
The routing override wins over `--rerank` (or outline's legacy `--provider`);
those options still control reranking. `--no-cache` bypasses cached decisions,
query variants and reranks. Decision keys include model endpoint and model name.
An unavailable decider falls back to the heuristic plan, with a stderr warning.

Search appends model-reported missing libraries as `kind: "gap"` rows. These have
`id: 0` and are not fetchable documentation. Real hits precede gap rows, and gap
rows do not count toward a successful search. Outline returns real entries only.
A gap warns that neighboring results do not document the missing library.

## Freshness and exits

Freshness reports `release` and `built_year` when known, plus `age_years` and
`stale`. Staleness means the local ingest year is more than two calendar years
old, not that the upstream release is obsolete. Missing timestamps have no known
age and are not automatically marked stale.

| Exit | Meaning |
| --- | --- |
| 0 | Success (including stale `fresh` without `--check`) |
| 2 | No usable search/outline results, or unknown freshness target |
| 3 | `get` ID does not exist |
| 5 | `fresh --check` found a stale snapshot |

Argument parsing and other operational errors may also be nonzero; inspect stderr.

## HTTP transport

`aemon serve --jobs 4` shares a listener across four workers; `--jobs 0` uses the
available CPU count. **Authentication is mandatory**, including `/health`.
Missing, invalid or duplicate bearer credentials receive HTTP 401 before any
command is parsed or executed. The server refuses to listen without a valid token.

The server and HTTP client use the same credential sources, in priority order:

1. `AEMON_API_TOKEN` (the token itself; useful for a secret manager).
2. `AEMON_API_TOKEN_FILE` (a path to a private token file).
3. `~/.config/aemon/token`.

An explicitly configured empty/invalid value fails; it never silently falls back.
A token is 32–512 ASCII letters, digits or `-._~+/=`. Generate a random secret;
length alone does not make a chosen password secure. On Unix the file must have
no group/other permissions (`chmod 600`). A single trailing newline is accepted.

Create a token once, without overwriting an existing credential:

```sh
(umask 077; set -C; mkdir -p "$HOME/.config/aemon";
 openssl rand -hex 32 > "$HOME/.config/aemon/token")
```

Securely provision the same token on the client and server. The CLI reads it
automatically; normal query commands do not gain a token argument. Do not put the
token in a URL or command-line flag. Tokens are never included in JSON reports,
error messages, or server startup logs, and token environment variables are
removed from the server's command subprocesses. Restart the server after rotation.

Use loopback behind an HTTPS reverse proxy for network access. The CLI refuses
to send a bearer token over non-loopback plain HTTP, and never follows redirects.
SSH transport remains available and uses SSH keys, not this token. Raw API clients
must send `Authorization: Bearer <token>` over a secure connection.

`POST /rpc` accepts `{"args":["search","connect","--json"]}`. Its reply wraps
CLI output as `{"stdout":"...","stderr":"...","code":0}`. Parse stdout again
to read the CLI envelope. HTTP 200 means the CLI executed, not that its exit code
was zero. Malformed argv is HTTP 400, forbidden commands/options are 403, and
bodies over 64 KiB are 413. Search may update model caches, but corpus mutations,
`crawl` commands other than `status`, client-selected databases/remotes, and
`sources --out` are forbidden.

The integration suite builds a synthetic docset in a temporary directory, invokes
the real binary, and uses only loopback HTTP model fixtures. It does not ingest
into the user's corpus or require a running model service. Builds and tests run
in CI.
