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
49 changes: 49 additions & 0 deletions .changeset/cli-contract-align.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
"@managers/server": minor
---

Align the `managers` CLI with the CLI contract (SPEC 0.2)

`serve` is now the name for running in the foreground, `/api/health` reports the
version it is running, `service status` answers in scriptable exit codes and
`--json`, there is a `service logs`, and the generated units are hardened. Ported
from Paddock 0.80–0.82, whose CLI this is.

**Behaviour changes a script can see.** These are why this is a minor:

- **Usage errors now exit `2`, not `1`.** An unknown command, flag or bad value
exits 2 and prints a short usage synopsis after the message. `1` now means only
that something genuinely failed.
- **`service status` now exits `3` or `4`.** `0` when installed, running and
answering; `3` when installed but not running, or running and not answering;
`4` when there is no unit. `service logs`, `start`, `stop` and `restart` exit
`4` with no unit too.
- **An `install`, `start` or `restart` that never answers now exits `1`**, not 0.
- **Linux service logs go to a file, not the journal.** Both streams append to
`<data-dir>/logs/service.log` (the path macOS already used, now one file rather
than two), which Managers rotates itself at 8 MB, keeping three generations.
An existing unit keeps the path it names until `managers service install` is
re-run.
- **The server's logs now go to stderr, not stdout**, so `serve`'s first stdout
line is `Managers <version>: <url>`. Docker, Kubernetes and the service units
collect both streams; a log shipper reading stdout ALONE is the one thing that
changes.

Everything else is additive:

- `managers serve` runs the server; **`managers start` stays an alias, for good.**
- `GET /api/health` answers `{ ok, version }`, with no auth.
- `managers service status --json`: installed / running / answering, the
installed and running versions, port, URL, pid, unit, log file and warnings.
- `managers service logs [-f] [-n <lines>]`, the last 50 lines by default.
- The main `--help` lists all seven `service` actions.
- Generated units: Node resolved through symlinks, a `PATH` without per-session
entries or missing directories, every systemd `ExecStart` word quoted, and
warnings for a vanished Node, a running-vs-installed version gap and (Linux)
lingering being off, which is now checked rather than printed at everyone.
- **macOS:** `install`, `start` and `restart` no longer lose a race with launchd
(`Bootstrap failed: 5: Input/output error`): they wait for a bootout to finish,
and retry a bootstrap that returns launchd's race codes 5 or 37.
- **Linux:** a reinstall over a RUNNING service now restarts it.
`systemctl --user enable --now` does nothing to an active unit, so the old
process went on serving the old code.
72 changes: 72 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,78 @@ jobs:
- name: Unit + integration tests
run: npm test

# The CLI contract, checked from the outside by @edspencer/cli-conformance: `--version` is
# bare, `--help` exits 0, an unknown flag exits 2 with the usage after the message,
# `service status` exits 4 with nothing installed and its --json matches the shared schema,
# `serve`'s first stdout line is `Managers <version>: <url>`, and /api/health answers with
# that same version. `cli-contract.json` at the root says which checks apply and why the
# two that don't (`busy`, wave C1) don't — a NEWER runner's new check fails until this repo
# says whether it applies, which is the point.
#
# `--dir dist-npm`, not the repo root: Managers' publishable package is SYNTHESIZED from two
# private workspaces by scripts/make-npm-package.mjs (see RELEASING.md), so `npm pack` at the
# root would pack the private root manifest, which has no `bin` at all. `npm run pack:npm`
# stages the real thing and the runner packs that — the same tarball a user installs.
#
# This is the check that found the banner bug: with pino on stdout, a machine with no Claude
# login printed a JSON log line as `serve`'s first line. Nothing else in CI could see it.
conformance:
name: CLI conformance
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- run: npm ci
- name: Stage the npm package
run: npm run pack:npm
- name: Conformance
run: npx cli-conformance --dir dist-npm --config cli-contract.json

# `managers service …` against the REAL service manager: launchd's gui/<uid> domain on the
# macOS runner, systemd's user instance on the Ubuntu runner (with lingering on, so there
# is one). scripts/service-real.mjs stages and packs the npm package, installs it into a
# temporary prefix, then installs, kills, stops, starts, restarts and uninstalls the
# service, checking the exit codes and that the log file really receives the server's
# stdout. It writes the runner's real LaunchAgents / systemd user directory under the real
# label, which is why it runs only here and refuses without MANAGERS_REAL_SERVICE=1.
#
# This is the only place the service CAN be proven: the dev box is a container with tini
# as PID 1 — no systemd, not a Mac — so everything else about these units is covered by
# unit tests of the rendered file, which cannot catch a key launchd rejects or a
# `systemctl --user` that will not load what we wrote.
service:
name: Service (real ${{ matrix.os == 'macos-latest' && 'launchd' || 'systemd' }})
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- run: npm ci
# A `systemctl --user` needs a user manager, and a GitHub runner has none until
# lingering starts one. Without this every systemctl call fails on the bus address.
- name: Start a systemd user instance (Linux)
if: runner.os == 'Linux'
run: |
sudo loginctl enable-linger "$USER"
for i in $(seq 1 20); do [ -S "/run/user/$(id -u)/bus" ] && break; sleep 0.5; done
echo "XDG_RUNTIME_DIR=/run/user/$(id -u)" >> "$GITHUB_ENV"
echo "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus" >> "$GITHUB_ENV"
- name: The service lifecycle, for real
env:
MANAGERS_REAL_SERVICE: "1"
run: node scripts/service-real.mjs

# Fails on a high/critical npm advisory that is not a documented exception
# (docs/security/npm-audit.md). Reads only the lockfile, so no `npm ci`.
audit:
Expand Down
19 changes: 19 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,25 @@ npm run test:e2e # Playwright journeys against the real server + a fa

The tell that you are looking at contention rather than a regression: the
failures pass when re-run in isolation.
- **The CLI contract** is checked from the outside by
[`@edspencer/cli-conformance`](https://github.com/edspencer/cli-contract), which packs the
package, installs it into a temporary prefix and runs the installed `managers` with a
throwaway home:

```bash
npm run pack:npm # stage dist-npm first
npx cli-conformance --dir dist-npm --config cli-contract.json
```

**`--dir dist-npm` is not optional.** The publishable `@edspencer/managers` is synthesized
from the two private workspaces (see [RELEASING.md](RELEASING.md)), so `npm pack` at the
repo root packs the private root manifest, which has no `bin`. `cli-contract.json` lists
every check the runner has and why the ones that do not apply yet do not — a new check in
a newer runner fails until this repo says which it is.

It is worth running by hand when you touch the CLI, because it checks things no unit test
can see: that `serve`'s FIRST stdout line is `Managers <version>: <url>` (it found a JSON
log record there), and that `service status --json` matches the contract's shared schema.
- More on the test layers: [docs/TESTING.md](docs/TESTING.md).

## The demo reel
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ docker run -d --name managers -p 127.0.0.1:7234:7234 -v /srv/managers-data:/data

Each GitHub Release also carries a self-contained tarball.

**Commands.** Bare `managers` runs the server; `managers serve` is the same thing
said out loud (`managers start` is a permanent alias). `managers service install`
runs it in the background from login (a launchd LaunchAgent on macOS, a
`systemd --user` unit on Linux), with `uninstall`, `start`, `stop`, `restart`,
`status [--json]` and `logs [-f] [-n <lines>]`. `service status` exits **0** when
it is up and answering, **3** when installed but not, and **4** when there is no
unit; a bad command, flag or value exits **2**. The CLI follows the shared
[CLI contract](https://github.com/edspencer/cli-contract) (`cli-contract.json`
says which of its checks apply).

## Quick start from a checkout

You need **Node 22+**. Build once:
Expand Down
50 changes: 50 additions & 0 deletions cli-contract.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"$schema": "./node_modules/@edspencer/cli-conformance/schemas/cli-contract.schema.json",
"name": "Managers",
"serve": {
"args": [
"serve",
"--port",
"{port}",
"--host",
"127.0.0.1",
"--data-dir",
"{home}/managers"
],
"timeoutMs": 60000
},
"env": {
"MANAGERS_DATA_DIR": "{home}/managers",
"MANAGERS_DRIVE_MODE": "batch",
"MANAGERS_ALLOW_BATCH_DRIVE": "1",
"MANAGERS_AUTH_MODE": "none",
"MANAGERS_DANGEROUSLY_ALLOW_NO_AUTH": null,
"MANAGERS_PROJECTS_DIR": null,
"MANAGERS_AUTH_JWKS_URL": null,
"MANAGERS_AUTH_JWT_HEADER": null,
"MANAGERS_SELF_MCP": null,
"MANAGERS_SELF_MCP_WRITE": null,
"MANAGERS_SELF_MCP_PROJECTS": null,
"CLAUDE_CODE_OAUTH_TOKEN": null,
"ANTHROPIC_API_KEY": null,
"CLAUDE_CONFIG_DIR": null,
"HOST": null,
"PORT": null,
"NODE_ENV": null
},
"checks": {
"version": true,
"help": true,
"unknown-flag": true,
"service-status": true,
"service-status-json": true,
"busy": {
"skip": "no `managers busy` until wave F2 of the CLI-contract rollout"
},
"busy-json": {
"skip": "no `managers busy` until wave F2 of the CLI-contract rollout"
},
"serve-banner": true,
"serve-health": true
}
}
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"devDependencies": {
"@changesets/changelog-github": "^0.5.2",
"@changesets/cli": "^2.31.0",
"@edspencer/cli-conformance": "^0.2.0",
"@playwright/test": "^1.61.0",
"playwright": "^1.61.0"
},
Expand Down
31 changes: 18 additions & 13 deletions packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import fastifyStatic from "@fastify/static";
import fastifyMultipart from "@fastify/multipart";
import fastifySwagger from "@fastify/swagger";
import fastifySwaggerUi from "@fastify/swagger-ui";
import { createRequire } from "node:module";
import { promises as fs } from "node:fs";
import path from "node:path";
import { loadPaddockConfig, type PaddockConfig } from "./config.js";
Expand Down Expand Up @@ -67,17 +66,10 @@ import { ensureDataRepo, dataGitInitEnabled } from "./managers/data-repo.js";
import { ManagersState } from "./managers/state.js";
import { Autocommitter } from "./managers/autocommit.js";
import { DataSync } from "./managers/data-sync.js";
// One source of truth for "which Managers is this?" — the OpenAPI document,
// /api/health and the management MCP handshake all read it (version.ts).
import { MANAGERS_VERSION } from "./version.js";

// Resolve the package version at runtime (dist/app.js → ../package.json) so the
// generated OpenAPI document's info.version tracks the release without a build step.
const pkgVersion: string = (() => {
try {
const require = createRequire(import.meta.url);
return (require("../package.json") as { version?: string }).version ?? "0.0.0";
} catch {
return "0.0.0";
}
})();

export interface BuiltApp {
app: FastifyInstance;
Expand Down Expand Up @@ -160,7 +152,20 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<BuiltApp> {
installHerdctlBridgeLoopbackBind();

const app = Fastify({
logger: { level: cfg.logLevel },
// **Logs go to stderr, not stdout**, and that is load-bearing rather than
// tidy. SPEC §3 of the CLI contract requires `serve`'s FIRST stdout line to
// be `Managers <version>: <url>` — the line a script reads to find the URL —
// and boot logging is emitted before the server can know it has bound. With
// pino on stdout, a machine with no Claude login (every CI runner, every
// fresh install) put `{"level":40,…,"msg":"no Claude credentials found…"}`
// there first, so the first line was a JSON log record. The conformance
// runner caught it; nothing else would have.
//
// Nothing loses the logs: Docker and Kubernetes collect both streams, and
// the service units send stdout and stderr to the same file (SPEC §7). A log
// shipper configured for stdout ALONE is the one thing that changes, which
// is why the changeset says so.
logger: { level: cfg.logLevel, stream: process.stderr },
});

// --- safe-by-default bind guard (#435) --------------------------------
Expand Down Expand Up @@ -497,7 +502,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<BuiltApp> {
readImage(path.join("icons", "icon-192.png"), "image/png"),
readImage(path.join("icons", "favicon-32.png"), "image/png"),
]);
await app.register(fastifySwagger, buildSwaggerOptions(pkgVersion, cfg.auth));
await app.register(fastifySwagger, buildSwaggerOptions(MANAGERS_VERSION, cfg.auth));
await app.register(
fastifySwaggerUi,
buildSwaggerUiOptions({
Expand Down
Loading
Loading