From 7e780515acad5fbea30457b6edcf2c5464a9d1ec Mon Sep 17 00:00:00 2001 From: yuez Date: Thu, 22 Oct 2026 15:47:48 +0800 Subject: [PATCH] feat(cli)!: merge the daemon into `pi2` as the `daemon` subcommand `pi2 daemon [start] [flags]` now starts the web-console daemon. The `pi2d` executable, its bin entry and its entry module are removed: the daemon keeps its lock -> token -> plugin socket -> listen -> daemon.json lifecycle, its single stdout line (`pi2 daemon listening on ...`) and the signal handling that leaves managed nvim instances running. Service files are renamed to `pi2.service` / `com.pi2.daemon`, and the smoke and e2e harnesses start the daemon through `pi2 daemon`. BREAKING CHANGE: the `pi2d` command no longer exists; use `pi2 daemon` (or `pi2 daemon start`). Existing systemd/launchd units installed under the old names must be reinstalled with `pi2 install-service --write`. --- README.md | 14 +-- docs/deployment.md | 111 ++++++++++++++-------- docs/e2e-report.md | 8 +- docs/e2e.md | 16 ++-- docs/protocol.md | 4 +- package.json | 9 +- scripts/e2e/api-e2e.mjs | 13 ++- scripts/e2e/attention-ext.ts | 4 +- scripts/e2e/full-e2e.sh | 8 +- scripts/e2e/host-init.lua | 2 +- scripts/e2e/lib.sh | 14 +-- scripts/e2e/ui-e2e.mjs | 4 +- scripts/e2e/visual.sh | 2 +- scripts/smoke.sh | 27 +++--- src/cli/{pi2d.ts => daemon.ts} | 57 +++-------- src/cli/doctor.ts | 8 +- src/cli/listen.ts | 2 +- src/cli/lock.ts | 4 +- src/cli/logger.ts | 4 +- src/cli/pi2.ts | 20 +++- src/cli/service.ts | 21 ++-- src/cli/token.ts | 4 +- src/cli/util.ts | 2 +- src/cli/wiring.ts | 2 +- src/config.ts | 2 +- src/core/interfaces.ts | 2 +- src/daemon/auth.ts | 4 +- test/cli/{pi2d.test.ts => daemon.test.ts} | 15 +-- test/cli/helpers.ts | 6 +- test/cli/pi2.test.ts | 73 ++++++++++---- test/cli/service.test.ts | 47 ++++----- test/daemon/harness.ts | 6 +- test/instances/helpers.ts | 2 +- test/workspaces/discovery.test.ts | 2 +- test/workspaces/helpers.ts | 2 +- test/workspaces/registry.test.ts | 2 +- test/workspaces/store.test.ts | 2 +- web/tests/chat.reducer.test.tsx | 2 +- 38 files changed, 295 insertions(+), 232 deletions(-) rename src/cli/{pi2d.ts => daemon.ts} (86%) rename test/cli/{pi2d.test.ts => daemon.test.ts} (92%) diff --git a/README.md b/README.md index ad9de4f..6f0b075 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ -# pi2d — pi2 web console daemon +# pi2 daemon — pi2 web console daemon The always-on web side of [pi2.nvim](https://github.com/…/pi2.nvim). It is a **router + supervisor**, not an agent runtime: ``` -browser ──HTTP/WS──▶ pi2d ──JSONL unix socket──▶ one nvim per workspace (pi2.nvim) - └── one pi --mode rpc per active session +browser ──HTTP/WS──▶ pi2 daemon ──JSONL unix socket──▶ one nvim per workspace (pi2.nvim) + └── one pi --mode rpc per active session ``` Hard rules (see `docs/protocol.md`): -1. `pi2d` never spawns `pi`, never reads session JSONL, never owns session state. +1. `pi2 daemon` never spawns `pi`, never reads session JSONL, never owns session state. 2. A workspace maps to **exactly one** managed nvim instance. 3. All mutations are commands relayed to the plugin; the plugin (inside nvim) is the single source of truth. 4. The web client keeps a render cache only; a `snapshot` from the plugin replaces it wholesale. @@ -22,7 +22,9 @@ pnpm test pnpm dev # starts on 127.0.0.1:7676 ``` -The plugin starts the daemon lazily when it is not running; you normally do not start it by hand. +The daemon is the `pi2 daemon` subcommand of the single shipped `pi2` binary — there is no +separate executable. The plugin starts it lazily when it is not running; you normally do not +start it by hand. ## Layout @@ -32,7 +34,7 @@ The plugin starts the daemon lazily when it is not running; you normally do not | `src/daemon/` | HTTP/WS/SSE, auth, static assets, routing, event relay | | `src/instances/` | discovery, lazy spawn, single-instance enforcement, crash handling | | `src/workspaces/` | workspace registry, disk discovery, aliases/trust | -| `src/cli/` | `pi2d` (daemon) and `pi2` (attach/status/doctor) | +| `src/cli/` | `pi2` — the `daemon` subcommand plus `attach`/`status`/`doctor` | | `fixtures/` | golden event streams + expected session state (shared with pi2.nvim tests) | | `docs/protocol.md` | the wire contract (browser ↔ daemon ↔ plugin) | diff --git a/docs/deployment.md b/docs/deployment.md index 1f1d7b5..c09a2e0 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1,14 +1,15 @@ # Deployment and operations -`pi2d` is the pi2 web-console daemon. It owns the HTTP/WS surface, the +`pi2 daemon` is the pi2 web-console daemon. It owns the HTTP/WS surface, the workspace registry, the instance supervisor (one managed nvim per workspace) -and the device/CLI auth. This document covers running it, its runtime files, -the `pi2` CLI and the day-to-day ops commands. +and the device/CLI auth. It is **a subcommand of the single shipped `pi2` +binary**, not a separate executable. This document covers running it, its +runtime files, the `pi2` CLI and the day-to-day ops commands. ``` -browser ──HTTP + WS/SSE──▶ pi2d ──JSONL over unix socket──▶ plugin (nvim) - ▲ - pi2 CLI │ (HTTP, local admin token) +browser ──HTTP + WS/SSE──▶ pi2 daemon ──JSONL over unix socket──▶ plugin (nvim) + ▲ + pi2 CLI │ (HTTP, local admin token) ``` Contents @@ -21,6 +22,7 @@ Contents 6. [Ports and the singleton lock](#6-ports-and-the-singleton-lock) 7. [Authentication](#7-authentication) 8. [The `pi2` CLI](#8-the-pi2-cli) + - [`pi2 daemon [start]`](#80-pi2-daemon-start) 9. [Services (systemd / launchd)](#9-services-systemd--launchd) 10. [Logs and health](#10-logs-and-health) 11. [Restart and shutdown semantics](#11-restart-and-shutdown-semantics) @@ -44,41 +46,55 @@ Contents ```bash pnpm install -pnpm build # tsc -> dist/ (dist/cli/pi2d.js, dist/cli/pi2.js) +pnpm build # tsc -> dist/ (dist/cli/pi2.js) pnpm --dir web build # optional: web/dist for the browser console ``` -`pi2d` serves the browser console from `/web/dist` (or `PI2_STATIC_DIR`). +The daemon serves the browser console from `/web/dist` (or `PI2_STATIC_DIR`). Without it `/` returns 404/SPA fallback behaviour and `/api/v1/health` reports `static=FAIL`; the API and `pi2` keep working. -Binaries: `dist/cli/pi2d.js` (daemon, `pi2d`) and `dist/cli/pi2.js` (client, -`pi2`). Both are ESM and start with a `#!` line. +There is exactly one built binary, `dist/cli/pi2.js` (client commands **and** the +`daemon` subcommand). It is ESM and starts with a `#!` line. ## 3. Running the daemon +The daemon is a subcommand of the single `pi2` binary (there is no separate +executable to install or ship): + ```bash -node dist/cli/pi2d.js --foreground # or: pnpm dev (tsx watch) +node dist/cli/pi2.js daemon --foreground # or: pnpm dev (tsx watch) ``` +`pi2 daemon`, `pi2 daemon start` (alias) and `pi2 daemon --foreground` all start +the same foreground process — `main` is dispatched from `src/cli/pi2.ts` to +`src/cli/daemon.ts` and the `start` positional is dropped before parsing. There +is no detaching mode; that is what the systemd/launchd units below rely on. + +`pi2 daemon --help` prints the usage block (`Usage: pi2 daemon [start] [options]`), +`pi2 daemon --version` prints `pi2 `, and an unknown daemon positional +exits `2` without starting anything. + Exactly one line goes to **stdout**: ``` -pi2d listening on http://127.0.0.1:7676 +pi2 daemon listening on http://127.0.0.1:7676 ``` Every log record is JSONL on **stderr** (that is what systemd/launchd capture). +Every daemon error is one line on stderr prefixed `pi2: `. -Flags: +Flags (`pi2 daemon [start] …`): | Flag | Meaning | |---|---| -| `--port ` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) | +| `--port `, `-p ` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) | | `--host ` | bind address (default `127.0.0.1`) | | `--static-dir

` | built web UI directory | -| `--force` | take the lock even if another `pi2d` holds it | +| `--force`, `-f` | take the lock even if another `pi2 daemon` holds it | | `--foreground` | stay attached to the terminal (default; used by unit files) | -| `--version`, `--help` | print and exit | +| `--version`, `-V` | print `pi2 ` and exit | +| `--help`, `-h` | print the usage block and exit | Flags are applied to the environment before the config is loaded, so `--port 8000` is equivalent to `PI2_PORT=8000`. @@ -131,8 +147,8 @@ overwritten on the next start. ## 6. Ports and the singleton lock -- One daemon per runtime dir. A second `pi2d` exits `1` with - `pi2d: another pi2d is running (pid …, port …); use --force to override`. +- One daemon per runtime dir. A second `pi2 daemon` exits `1` with + `pi2: another pi2 daemon is running (pid …, port …); use --force to override`. - `--force` takes over the lock; the displaced daemon keeps serving until it exits, and it will *not* delete the new lock on shutdown (ownership is checked by pid + `daemonId`). @@ -150,8 +166,8 @@ Two token kinds: 1. **Device tokens** (paired phones/laptops): created by `POST /api/v1/pair` (redeem) or `pair.create`; only SHA-256 hashes are stored in `PI2_DATA_DIR/devices.json`. -2. **Local CLI token**: `PI2_RUNTIME_DIR/cli.token`, minted by `pi2d` on each - start. Any request carrying it authenticates as the synthetic device +2. **Local CLI token**: `PI2_RUNTIME_DIR/cli.token`, minted by `pi2 daemon` on + each start. Any request carrying it authenticates as the synthetic device `{id:"local-cli", name:"local CLI", scopes:["read","steer","control","admin"]}` (constant-time compare, never persisted, not revocable, not listed by `GET /api/v1/devices`). Rotating the file invalidates the old value @@ -168,6 +184,22 @@ authenticated (auth runs before routing). `PI2_RUNTIME_DIR`, so it needs no flags. Every command exits non-zero with a one-line `pi2: …` message on failure. +### 8.0 `pi2 daemon [start]` + +```bash +pi2 daemon # foreground; the plugin/browser needs this running +pi2 daemon start # same thing (explicit subcommand alias) +pi2 daemon --foreground # same thing (the flag is the default) +pi2 daemon -p 0 # ephemeral port +pi2 daemon --help # Usage: pi2 daemon [start] [options] +``` + +All three forms start the identical foreground process; the `start` positional is +dropped before the flag parser runs, and an unknown daemon positional exits `2`. +The daemon is dispatched *inside* `pi2` (`src/cli/pi2.ts` → `src/cli/daemon.ts`): +it is not a separate executable, nothing is re-exec'd, and there is no detaching +mode. Flags, stdout contract and startup order: [§3](#3-running-the-daemon). + ### 8.1 `pi2 attach [path]` ```bash @@ -242,21 +274,21 @@ commands. The CLI never executes `systemctl`/`launchctl`. ```bash pi2 install-service --dry-run # inspect, nothing written -pi2 install-service --write # ~/.config/systemd/user/pi2d.service +pi2 install-service --write # ~/.config/systemd/user/pi2.service systemctl --user daemon-reload -systemctl --user enable --now pi2d.service +systemctl --user enable --now pi2.service ``` The unit is rendered with absolute paths: ```ini [Unit] -Description=pi2 daemon (pi2d) +Description=pi2 daemon After=network.target [Service] Type=simple -ExecStart=/usr/bin/node /repo/dist/cli/pi2d.js --foreground +ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground Environment=PATH=/usr/local/bin:/usr/bin:/bin Restart=on-failure RestartSec=2 @@ -268,13 +300,14 @@ WantedBy=default.target ``` `XDG_CONFIG_HOME` is honoured for the target directory. On macOS the same -command writes `~/Library/LaunchAgents/com.pi2.pi2d.plist` (`RunAtLoad`, -`KeepAlive`, absolute node + script paths, `StandardOutPath`/`StandardErrorPath` -under `PI2_STATE_DIR`) and prints: +command writes `~/Library/LaunchAgents/com.pi2.daemon.plist` (`RunAtLoad`, +`KeepAlive`, absolute node + script paths, `ProgramArguments` +`node /repo/dist/cli/pi2.js daemon --foreground`, `StandardOutPath`/ +`StandardErrorPath` under `PI2_STATE_DIR`) and prints: ```bash -launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.pi2d.plist -launchctl enable gui/$(id -u)/com.pi2.pi2d +launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist +launchctl enable gui/$(id -u)/com.pi2.daemon ``` `uninstall-service --write` removes the file and prints the disable commands. @@ -283,9 +316,10 @@ For a login-less service to keep running on Linux enable linger ## 10. Logs and health -- `pi2d` logs JSONL to stderr: `systemctl --user status pi2d` / - `journalctl --user -u pi2d -f` on Linux, `~/Library/Logs/pi2/pi2d.log` on - macOS. Raise verbosity with `PI2_LOG_LEVEL=debug` (in the unit's +- `pi2 daemon` logs JSONL to stderr: `systemctl --user status pi2` / + `journalctl --user -u pi2 -f` on Linux (`pi2.service`), and + `~/Library/Logs/pi2/pi2-daemon.log` (`pi2-daemon.err.log` for stderr) on macOS. + Raise verbosity with `PI2_LOG_LEVEL=debug` (in the unit's `Environment=` line) . - Managed nvim output: `PI2_STATE_DIR/instances/.log`. - `GET /api/v1/health` → `{ok, items:[{name, ok, detail}]}` (`instances`, @@ -301,7 +335,7 @@ For a login-less service to keep running on Linux enable linger ## 11. Restart and shutdown semantics -- **SIGINT/SIGTERM/SIGHUP** (`pi2d`): close HTTP + WS, close the plugin socket, +- **SIGINT/SIGTERM/SIGHUP** (`pi2 daemon`): close HTTP + WS, close the plugin socket, release `daemon.lock`/`daemon.json`, exit `0`. **Managed nvim processes are not stopped** — they keep running and reconnect (exponential backoff, 200 ms → 5 s) the next time the daemon starts. @@ -319,22 +353,23 @@ For a login-less service to keep running on Linux enable linger bash scripts/smoke.sh ``` -Builds, starts `pi2d` on an ephemeral port with throwaway +Builds, starts `pi2 daemon` on an ephemeral port with throwaway `PI2_RUNTIME_DIR`/`PI2_DATA_DIR`/`PI2_STATE_DIR`, waits for `daemon.json`, then asserts: `/api/v1/info` (200, `v=1`), `/api/v1/health` (200 ok), `/` (200 html from `web/dist`), `/api/v1/nope` (404 with token, 401 without), `/api/v1/workspaces` (200 array with the CLI token, 401 without/with a bogus token), the `cli.token` format/mode, the lock payload, and a clean `SIGTERM` exit with lock + `daemon.json` removed. Prints one `PASS` line per assertion. -`PI2_SMOKE_KEEP=1` keeps the temp dir (and `pi2d` log) for debugging. +`PI2_SMOKE_KEEP=1` keeps the temp dir (and the `pi2-daemon.log` daemon log) for +debugging. ## 13. Troubleshooting | Symptom | Cause / fix | |---|---| -| `pi2d: another pi2d is running (pid …)` | a live daemon owns this runtime dir. Stop it, or `--force` | -| `pi2: no running pi2d (…/daemon.json missing)` | daemon not started, or started with a different `PI2_RUNTIME_DIR` | -| `pi2: missing CLI token (…/cli.token)` | token deleted or daemon restarted; restart `pi2d` | +| `pi2: another pi2 daemon is running (pid …)` | a live daemon owns this runtime dir. Stop it, or `--force` | +| `pi2: no running pi2 daemon (…/daemon.json missing)` | daemon not started, or started with a different `PI2_RUNTIME_DIR` | +| `pi2: missing CLI token (…/cli.token)` | token deleted or daemon restarted; restart `pi2 daemon` | | `401 E_UNAUTHORIZED` from `curl` | send `Authorization: Bearer $(cat $PI2_RUNTIME_DIR/cli.token)` | | `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) | | `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) | diff --git a/docs/e2e-report.md b/docs/e2e-report.md index ad6b4a5..7396f1f 100644 --- a/docs/e2e-report.md +++ b/docs/e2e-report.md @@ -12,7 +12,7 @@ | node | v22.23.1 | | nvim | 0.12.6 | | pi | 1.3.0 | -| daemon | `pi2d` @ `31f3630` + working-tree fixes | +| daemon | `pi2 daemon` @ `31f3630` + working-tree fixes | | plugin | `pi2.nvim` `feat/web-console` @ `ffec47c` + working-tree fixes | | browser | Chrome (Playwright 1.63, headless) | | model | `cliproxyapi` (real turns; `deepseek-v4-pro` in the browser run) | @@ -73,7 +73,7 @@ C3 dark/light screenshots · C4 zero unexpected console errors/pageerrors. is implemented; `subagent.dispatch` accepts the canonical `items[]` shape; `attention.respond` accepts the structured response table. -### Daemon (`pi2d`) +### Daemon (`pi2 daemon`) - Workspaces outside `PI2_WORKSPACE_ROOTS` returned `500 E_INTERNAL`; now `403 E_FORBIDDEN`. @@ -86,7 +86,7 @@ C3 dark/light screenshots · C4 zero unexpected console errors/pageerrors. - `/api/v1/info` gained additive `hostname`, `os`, `version`, `uptimeMs`, `pid`, `port`; `/health` reflects instance/workspace/auth state. -### Web (`pi2d/web`) +### Web (`web/`) - Pairing posted `pair.redeem` to the bearer-gated `/api/v1/cmd` → every pairing 401. The manual/scan flows now redeem the public `POST /api/v1/pair` @@ -124,7 +124,7 @@ C3 dark/light screenshots · C4 zero unexpected console errors/pageerrors. ## Reproduction ```bash -cd /home/yuez/Workspace/Neovim/pi2d +cd # the pi2 CLI/daemon checkout (this repository) bash scripts/e2e/run-all.sh # builds daemon + web, runs API then browser # individual suites diff --git a/docs/e2e.md b/docs/e2e.md index e9fb5d3..0770b53 100644 --- a/docs/e2e.md +++ b/docs/e2e.md @@ -9,8 +9,8 @@ processes that make the console real, and describes the harness that implements browser (React in web/dist) │ HTTP + WS ▼ -pi2d (src/) ── JSONL unix socket ──▶ headless nvim + pi2.nvim web layer - └── pi --mode rpc (real model) +pi2 daemon (src/) ── JSONL unix socket ──▶ headless nvim + pi2.nvim web layer + └── pi --mode rpc (real model) ``` Authority, highest first: @@ -83,7 +83,7 @@ markers, so the diff review does not depend on the model choosing to call the to Rules: - Before anything starts, `e2e_init` requires `node`, `nvim`, `pi`, `jq` and `curl`, a plugin - worktree with `lua/pi/web/commands.lua`, a built `dist/cli/pi2d.js`, and `host-init.lua`. + worktree with `lua/pi/web/commands.lua`, a built `dist/cli/pi2.js`, and `host-init.lua`. Missing pieces exit 2 with the artifacts path. - Never touch a daemon already running in the default runtime dir. `e2e_stop` terminates the daemon it started, then reaps every process whose command line contains `$E2E_ROOT` @@ -334,8 +334,8 @@ For every failed assertion: → fix the owning layer. 3. Fix in one layer at a time, with exclusive file ownership per subagent; never let two agents edit the same file concurrently. -4. Re-run the failed scenario, then the full suite. Unit tests (`vitest` in `pi2d` and - `pi2d/web`) must stay green after every fix. +4. Re-run the failed scenario, then the full suite. Unit tests (`vitest` in the daemon repo and + in `web/`) must stay green after every fix. 5. Do not mark a scenario PASS from a static grep or a screenshot alone; assert the observable behavior described above. @@ -355,7 +355,7 @@ the Playwright module/Chrome actually used, and one section per scenario with ev assertion. `ui-e2e.mjs` also copies its markdown to `/tmp/pi2-e2e-recon/e2e-ui-run.md`. Logs live in `$E2E_ROOT/logs/`: `.log` (build output + driver stderr) and -`pi2d.log` / `pi2d.stdout` for the daemon. +`daemon.log` / `daemon.stdout` for the `pi2 daemon` process. The summary must state which scenarios passed, which failed with observed vs expected, which were skipped and why (non-blocking only), and the command that reproduces the run. @@ -363,9 +363,9 @@ which were skipped and why (non-blocking only), and the command that reproduces ## 7. Commands ```bash -cd /home/yuez/Workspace/Neovim/pi2d +cd # the pi2 CLI/daemon checkout (this repository) -# backend only (A0–A12): tsc, then daemon + headless nvim + real pi +# backend only (A0–A12): tsc, then `pi2 daemon` + headless nvim + real pi bash scripts/e2e/run-api.sh # browser (B1–B14, C1–C4): also builds web/dist (pnpm), then Playwright diff --git a/docs/protocol.md b/docs/protocol.md index 6e584d9..d2ebc60 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -3,10 +3,10 @@ Single vocabulary, three surfaces. **The plugin inside nvim is the only authority for session state.** ``` -browser <──HTTP + WS/SSE──> pi2d <──JSONL over unix socket──> plugin (nvim) +browser <──HTTP + WS/SSE──> pi2 daemon <──JSONL over unix socket──> plugin (nvim) ``` -- `pi2d` never spawns `pi`, never parses session JSONL, never stores session state. +- `pi2 daemon` never spawns `pi`, never parses session JSONL, never stores session state. - The browser keeps a **render cache** only; a `snapshot` replaces it wholesale. - One workspace maps to exactly one managed nvim instance. diff --git a/package.json b/package.json index 3338ae2..225b9ef 100644 --- a/package.json +++ b/package.json @@ -1,24 +1,23 @@ { - "name": "pi2d", + "name": "pi2-web-daemon", "version": "0.1.0", "private": true, "type": "module", - "description": "pi2 web console daemon: HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim", + "description": "pi2 web console daemon (`pi2 daemon`): HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim", "engines": { "node": ">=22" }, "bin": { - "pi2d": "./dist/cli/pi2d.js", "pi2": "./dist/cli/pi2.js" }, "scripts": { - "dev": "tsx watch src/cli/pi2d.ts", + "dev": "tsx watch src/cli/pi2.ts daemon", "build": "tsc -p tsconfig.json", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", "test:watch": "vitest", "lint": "tsc -p tsconfig.json --noEmit", - "start": "node dist/cli/pi2d.js --foreground", + "start": "node dist/cli/pi2.js daemon --foreground", "smoke": "bash scripts/smoke.sh" }, "dependencies": { diff --git a/scripts/e2e/api-e2e.mjs b/scripts/e2e/api-e2e.mjs index 1c36338..1f478ef 100644 --- a/scripts/e2e/api-e2e.mjs +++ b/scripts/e2e/api-e2e.mjs @@ -49,6 +49,9 @@ const STATE_DIR = process.env.PI2_STATE_DIR ?? join(E2E_ROOT, "state"); const WS_URL = `${BASE.replace(/^http/, "ws")}/ws`; const REPORT_DIR = join(E2E_ROOT, "report"); const RECON_REPORT = process.env.E2E_RECON_REPORT ?? "/tmp/pi2-e2e-recon/e2e-api-run.md"; +// Repository root (this driver lives in `/scripts/e2e/`), so the reports +// can print a reproducible command without hardcoding a checkout path. +const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "../.."); const TURN_MS = 120_000; const ABORT_SETTLE_MS = 10_000; @@ -2907,12 +2910,12 @@ function collectLogTails() { const tail = tailOf(path); if (tail) targets.push({ label, path, tail }); }; - push("daemon", join(E2E_ROOT, "logs", "pi2d.log")); - push("daemon.stdout", join(E2E_ROOT, "logs", "pi2d.stdout")); + push("daemon", join(E2E_ROOT, "logs", "daemon.log")); + push("daemon.stdout", join(E2E_ROOT, "logs", "daemon.stdout")); for (const path of findLogs(join(STATE_DIR, "instances"))) push(`instance ${path.split("/").slice(-2).join("/")}`, path); for (const path of findLogs(STATE_DIR)) { if (targets.some((target) => target.path === path)) continue; - if (/pi2-web|pi2d|instance/.test(path)) push(`state ${path.split("/").slice(-2).join("/")}`, path); + if (/pi2-web|pi2-daemon|instance/.test(path)) push(`state ${path.split("/").slice(-2).join("/")}`, path); } return targets; } @@ -2952,14 +2955,14 @@ function renderSummaryMarkdown(results, counts, durationMs) { lines.push("## Reproduction"); lines.push(""); lines.push("```bash"); - lines.push("cd /home/yuez/Workspace/Neovim/pi2d && E2E_SKIP_BUILD=1 bash scripts/e2e/run-api.sh"); + lines.push(`cd "${REPO_ROOT}" && E2E_SKIP_BUILD=1 bash scripts/e2e/run-api.sh`); lines.push("```"); return `${lines.join("\n")}\n`; } function renderReconMarkdown(results, counts, durationMs, logs) { const lines = []; - lines.push("# pi2d API/WS E2E (A0–A12) — run report"); + lines.push("# pi2 daemon API/WS E2E (A0–A12) — run report"); lines.push(""); lines.push(`- driver: \`${join(dirname(fileURLToPath(import.meta.url)), "api-e2e.mjs")}\``); lines.push(`- base: \`${BASE}\` · root: \`${E2E_ROOT}\``); diff --git a/scripts/e2e/attention-ext.ts b/scripts/e2e/attention-ext.ts index 9ff2c96..27068a4 100644 --- a/scripts/e2e/attention-ext.ts +++ b/scripts/e2e/attention-ext.ts @@ -1,5 +1,5 @@ /** - * Test-only pi extension for the pi2d API/WS end-to-end suite (docs/e2e.md A11). + * Test-only pi extension for the pi2 daemon API/WS end-to-end suite (docs/e2e.md A11). * * The suite must prove the pre-execution attention/diff contract without a real * terminal UI: @@ -18,7 +18,7 @@ * * The title payload uses the web console's documented diff shape * `{toolName, files:[{path, before, after}]}` (see - * `pi2d/web/src/features/chat/diff.ts:diffFilesFromPayload`), so the same JSON + * `web/src/features/chat/diff.ts:diffFilesFromPayload`), so the same JSON * drives both the plugin's attention classification and the web diff view. * * Determinism: the select is issued from the tool call (no timing tricks). A diff --git a/scripts/e2e/full-e2e.sh b/scripts/e2e/full-e2e.sh index 03a259f..5652f03 100755 --- a/scripts/e2e/full-e2e.sh +++ b/scripts/e2e/full-e2e.sh @@ -30,7 +30,7 @@ fail() { echo "--- daemon log ---"; tail -60 "$LOG" 2>/dev/null || true echo "--- instance logs ---"; ls -la "$STATE/instances" 2>/dev/null || true; tail -80 "$STATE"/instances/*.log 2>/dev/null || true echo "--- nvim web log ---"; find "$STATE" -name 'pi2-web.log' -exec tail -80 {} \; 2>/dev/null || true - echo "--- processes ---"; ps -eo pid,ppid,etime,args | grep -E "nvim|pi --mode|node .*pi2d" | grep -v grep || true + echo "--- processes ---"; ps -eo pid,ppid,etime,args | grep -E "nvim|pi --mode|node .*pi2\.js daemon" | grep -v grep || true echo "--- sessions endpoint ---"; curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/api/v1/workspaces/$WSID/sessions" 2>/dev/null | head -c 2000 || true echo echo "--- state ---"; ls -la "$STATE" "$RUN" 2>/dev/null || true @@ -39,13 +39,13 @@ fail() { command -v jq >/dev/null || { echo "jq is required"; exit 2; } command -v pi >/dev/null || { echo "pi CLI is required"; exit 2; } -[ -f "$REPO/dist/cli/pi2d.js" ] || { echo "run: npx tsc -p tsconfig.json"; exit 2; } +[ -f "$REPO/dist/cli/pi2.js" ] || { echo "run: npx tsc -p tsconfig.json"; exit 2; } echo "==> workspace $WS" printf '# e2e\n' > "$WS/README.md" -echo "==> starting pi2d" -node "$REPO/dist/cli/pi2d.js" --foreground --port 0 >"$LOG" 2>&1 & +echo "==> starting pi2 daemon" +node "$REPO/dist/cli/pi2.js" daemon --foreground --port 0 >"$LOG" 2>&1 & DPID=$! cleanup() { kill "$DPID" 2>/dev/null || true diff --git a/scripts/e2e/host-init.lua b/scripts/e2e/host-init.lua index 3435e72..eb06aa4 100644 --- a/scripts/e2e/host-init.lua +++ b/scripts/e2e/host-init.lua @@ -1,4 +1,4 @@ --- Init used by the pi2d end-to-end harness. +-- Init used by the pi2 daemon end-to-end harness. -- Minimal, hermetic: only the plugin under test on the runtimepath, with the -- web console enabled and diagnostics enabled. Setting up the plugin here also -- makes `pi.host` skip its own `setup()` call. diff --git a/scripts/e2e/lib.sh b/scripts/e2e/lib.sh index 46d918e..5985c87 100644 --- a/scripts/e2e/lib.sh +++ b/scripts/e2e/lib.sh @@ -71,8 +71,8 @@ e2e_init() { [ -n "$E2E_NVIM_BIN" ] || e2e_fail "nvim not found" [ -f "$E2E_PLUGIN/lua/pi/web/commands.lua" ] || e2e_fail "plugin worktree has no web layer: $E2E_PLUGIN" - [ -f "$E2E_REPO/dist/cli/pi2d.js" ] || - e2e_fail "dist/cli/pi2d.js missing; run e2e_build" + [ -f "$E2E_REPO/dist/cli/pi2.js" ] || + e2e_fail "dist/cli/pi2.js missing; run e2e_build" [ -f "$E2E_REPO/scripts/e2e/host-init.lua" ] || e2e_fail "host-init.lua missing" e2e_log "==> $suite root: $E2E_ROOT" @@ -95,12 +95,12 @@ e2e_build() { # Wait until the daemon publishes run/daemon.json, then environment-ready. e2e_start_daemon() { - local log="$E2E_ROOT/logs/pi2d.log" + local log="$E2E_ROOT/logs/daemon.log" : >"$log" - e2e_log "==> starting pi2d (isolated, port 0)" + e2e_log "==> starting pi2 daemon (isolated, port 0)" # `exec` makes $! the node process itself, not the wrapping subshell, so # the trap can actually stop the daemon. - (cd "$E2E_REPO" && exec node dist/cli/pi2d.js --foreground >"$E2E_ROOT/logs/pi2d.stdout" 2>"$log") & + (cd "$E2E_REPO" && exec node dist/cli/pi2.js daemon --foreground >"$E2E_ROOT/logs/daemon.stdout" 2>"$log") & E2E_DAEMON_PID=$! export E2E_DAEMON_PID @@ -109,7 +109,7 @@ e2e_start_daemon() { [ -f "$PI2_RUNTIME_DIR/daemon.json" ] && break kill -0 "$E2E_DAEMON_PID" 2>/dev/null || { tail -40 "$log" >&2 || true - e2e_fail "pi2d exited before writing daemon.json" + e2e_fail "pi2 daemon exited before writing daemon.json" } sleep 0.05 done @@ -202,7 +202,7 @@ e2e_pids() { local pid { ps -eo pid=,args= | grep -F -- "$E2E_ROOT" | grep -v -F -- 'grep -F' | awk '{print $1}' || true - for pid in $(pgrep -f 'pi2d|pi\.host|pi --mode rpc|nvim --headless' 2>/dev/null || true); do + for pid in $(pgrep -f 'pi2\.js daemon|pi\.host|pi --mode rpc|nvim --headless' 2>/dev/null || true); do if tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null | grep -Fxq "PI2_RUNTIME_DIR=$PI2_RUNTIME_DIR"; then echo "$pid" diff --git a/scripts/e2e/ui-e2e.mjs b/scripts/e2e/ui-e2e.mjs index 12ceb0b..1d5ecbc 100644 --- a/scripts/e2e/ui-e2e.mjs +++ b/scripts/e2e/ui-e2e.mjs @@ -62,7 +62,7 @@ fs.mkdirSync(SCREENS, { recursive: true }); fs.mkdirSync(REPORT_DIR, { recursive: true }); /* ------------------------------------------------------------------ */ -/* playwright resolution (not a pi2d dependency) */ +/* playwright resolution (not a daemon dependency) */ /* ------------------------------------------------------------------ */ const require_ = createRequire(import.meta.url); @@ -1568,7 +1568,7 @@ scenario("B7", "Abort: slow prompt → Abort button → Idle within 10 s, partia ctx.note(`abort status label: ${abortStatusLabel || "(none)"}`); const partial = (await streamArticles(page)).filter((article) => article.role === "assistant"); - ctx.check("partial assistant text remains", partial.length >= 1 && partial[0].text.length > 0, { + ctx.check("partial assistant text remains", partial.some((article) => article.text.length > 0), { expected: ">=1 assistant article with text", observed: partial.map((article) => short(article.text, 80)), }); diff --git a/scripts/e2e/visual.sh b/scripts/e2e/visual.sh index 407e3c8..2ca2f77 100755 --- a/scripts/e2e/visual.sh +++ b/scripts/e2e/visual.sh @@ -24,7 +24,7 @@ export PI2_NVIM_BIN="${PI2_NVIM_BIN:-$(command -v nvim)}" export PI2_NVIM_INIT="$REPO/scripts/e2e/host-init.lua" export PI2_E2E_PLUGIN="${PI2_E2E_PLUGIN:-/home/yuez/Workspace/Neovim/pi2.nvim-web}" -node "$REPO/dist/cli/pi2d.js" --foreground --port 0 >"$LOG" 2>&1 & +node "$REPO/dist/cli/pi2.js" daemon --foreground --port 0 >"$LOG" 2>&1 & DPID=$! cleanup() { kill "$DPID" 2>/dev/null || true; wait "$DPID" 2>/dev/null || true; } trap cleanup EXIT diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 5987a24..70fbf69 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -2,8 +2,8 @@ # # End-to-end smoke test for the pi2 daemon. # -# Builds the project, starts `pi2d` on an ephemeral port with throwaway runtime -# dirs, then asserts the HTTP surface (info/health/static/404/auth), the +# Builds the project, starts `pi2 daemon` on an ephemeral port with throwaway +# runtime dirs, then asserts the HTTP surface (info/health/static/404/auth), the # discovery file and a clean SIGTERM shutdown. # # Usage: bash scripts/smoke.sh @@ -20,7 +20,7 @@ export PI2_RUNTIME_DIR PI2_DATA_DIR PI2_STATE_DIR export PI2_PORT=0 export PI2_LOG_LEVEL="${PI2_LOG_LEVEL:-warn}" -LOG="$TMP/pi2d.log" +LOG="$TMP/pi2-daemon.log" DAEMON_JSON="$PI2_RUNTIME_DIR/daemon.json" LOCK="$PI2_RUNTIME_DIR/daemon.lock" TOKEN_FILE="$PI2_RUNTIME_DIR/cli.token" @@ -45,7 +45,7 @@ pass() { printf 'PASS %s\n' "$*"; } fail() { printf 'FAIL %s\n' "$*" >&2 if [[ -f "$LOG" ]]; then - printf '\n--- pi2d log ---\n' >&2 + printf '\n--- pi2 daemon log ---\n' >&2 tail -n 40 "$LOG" >&2 || true fi printf '\n--- tmp dir: %s ---\n' "$TMP" >&2 @@ -102,17 +102,16 @@ if ! npx tsc -p tsconfig.json >"$TMP/build.log" 2>&1; then cat "$TMP/build.log" >&2 fail "build failed" fi -[[ -f dist/cli/pi2d.js ]] || fail "dist/cli/pi2d.js missing after build" [[ -f dist/cli/pi2.js ]] || fail "dist/cli/pi2.js missing after build" -pass "build produced dist/cli/pi2d.js and dist/cli/pi2.js" +pass "build produced dist/cli/pi2.js" -printf '==> starting pi2d (port 0)\n' -node dist/cli/pi2d.js --foreground >"$TMP/stdout.log" 2>"$LOG" & +printf '==> starting pi2 daemon (port 0)\n' +node dist/cli/pi2.js daemon --foreground >"$TMP/stdout.log" 2>"$LOG" & DAEMON_PID=$! for _ in $(seq 1 200); do [[ -f "$DAEMON_JSON" ]] && break - kill -0 "$DAEMON_PID" 2>/dev/null || fail "pi2d exited before writing daemon.json" + kill -0 "$DAEMON_PID" 2>/dev/null || fail "pi2 daemon exited before writing daemon.json" sleep 0.05 done [[ -f "$DAEMON_JSON" ]] || fail "daemon.json was not written" @@ -134,8 +133,8 @@ pass "daemon.lock holds pid $DAEMON_PID" expect_json "body.protocolVersion === 1" "daemon.json protocolVersion === 1" "$DAEMON_JSON" -grep -q "^pi2d listening on http://127.0.0.1:$PORT$" "$TMP/stdout.log" || - fail "stdout line missing: expected 'pi2d listening on http://127.0.0.1:$PORT' (got: $(cat "$TMP/stdout.log"))" +grep -q "^pi2 daemon listening on http://127.0.0.1:$PORT$" "$TMP/stdout.log" || + fail "stdout line missing: expected 'pi2 daemon listening on http://127.0.0.1:$PORT' (got: $(cat "$TMP/stdout.log"))" pass "stdout announced http://127.0.0.1:$PORT" [[ -f "$TOKEN_FILE" ]] || fail "cli.token missing" @@ -175,19 +174,19 @@ pass "GET /api/v1/workspaces without a token -> 401" expect_status 401 GET /api/v1/workspaces -H "authorization: Bearer deadbeef" pass "GET /api/v1/workspaces with a bogus token -> 401" -printf '==> stopping pi2d (SIGTERM)\n' +printf '==> stopping pi2 daemon (SIGTERM)\n' kill -TERM "$DAEMON_PID" for _ in $(seq 1 100); do kill -0 "$DAEMON_PID" 2>/dev/null || break sleep 0.05 done -kill -0 "$DAEMON_PID" 2>/dev/null && fail "pi2d did not exit within 5s of SIGTERM" +kill -0 "$DAEMON_PID" 2>/dev/null && fail "pi2 daemon did not exit within 5s of SIGTERM" set +e wait "$DAEMON_PID" EXIT_CODE=$? set -e -[[ "$EXIT_CODE" -eq 0 ]] || fail "pi2d exited with code $EXIT_CODE" +[[ "$EXIT_CODE" -eq 0 ]] || fail "pi2 daemon exited with code $EXIT_CODE" pass "SIGTERM -> clean exit (code 0)" [[ ! -f "$LOCK" ]] || fail "daemon.lock was not removed on shutdown" diff --git a/src/cli/pi2d.ts b/src/cli/daemon.ts similarity index 86% rename from src/cli/pi2d.ts rename to src/cli/daemon.ts index 5bd8cf1..d0388e4 100644 --- a/src/cli/pi2d.ts +++ b/src/cli/daemon.ts @@ -1,6 +1,5 @@ -#!/usr/bin/env node /** - * `pi2d` — the pi2 daemon entry point. + * `pi2 daemon` — the pi2 web-console daemon entry point. * * Responsibilities (and nothing else): * 1. parse args / apply `--port|--host|--static-dir` to the config env @@ -9,12 +8,14 @@ * for local CLI access — a second daemon must never rotate the live token * 4. wire the real dependencies and listen (port 0 allowed, +1..+9 on a busy * default port), then publish `/daemon.json` - * 5. print exactly one line: `pi2d listening on http://host:port` + * 5. print exactly one line: `pi2 daemon listening on http://host:port` * 6. on SIGINT/SIGTERM close http + the plugin socket and release the lock — * **without** stopping nvim instances (they reconnect on the next start) + * + * This module is not an entry point: `src/cli/pi2.ts` dispatches `pi2 daemon` + * (optionally `pi2 daemon start`) to `main()`. */ import { randomUUID } from "node:crypto"; -import { fileURLToPath } from "node:url"; import { loadConfig, DEFAULT_PORT, type Config } from "../config.js"; import { ensureDir, runtimeDir } from "../core/paths.js"; import type { Logger } from "../core/interfaces.js"; @@ -22,23 +23,15 @@ import { PROTOCOL_VERSION } from "../protocol/types.js"; import { createLogger } from "./logger.js"; import { acquireLock, writeDaemonJson, type DaemonLockHandle } from "./lock.js"; import { cliTokenPath, writeCliToken } from "./token.js"; -import { - boolFlag, - errorMessage, - packageVersion, - parseArgs, - realpathOrSelf, - stringFlag, - UsageError, -} from "./util.js"; +import { boolFlag, errorMessage, packageVersion, parseArgs, stringFlag, UsageError } from "./util.js"; import { wireDaemon, type WiredDaemon } from "./wiring.js"; /** Extra attempts when the *default* port is taken (7676 → 7677 … 7685). */ export const DEFAULT_PORT_RETRIES = 9; -export const USAGE = `pi2d — pi2 daemon +export const USAGE = `pi2 daemon — pi2 daemon -Usage: pi2d [options] +Usage: pi2 daemon [start] [options] Options: --port TCP port (default ${DEFAULT_PORT}; 0 = ephemeral) @@ -137,7 +130,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions args = parseDaemonArgs(argv); } catch (error) { if (error instanceof UsageError) { - io.err(`pi2d: ${error.message}`); + io.err(`pi2: ${error.message}`); io.err(error.usage ?? USAGE); return 2; } @@ -149,7 +142,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions return 0; } if (args.version) { - io.out(`pi2d ${packageVersion()}`); + io.out(`pi2 ${packageVersion()}`); return 0; } @@ -166,7 +159,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions try { config = loadConfig(); } catch (error) { - io.err(`pi2d: ${errorMessage(error)}`); + io.err(`pi2: ${errorMessage(error)}`); return 1; } @@ -202,9 +195,9 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions lock.update({ port: server.port }); writeDaemonJson(lock.lock); // One machine-readable line; every log record goes to stderr. - io.out(`pi2d listening on ${server.url}`); + io.out(`pi2 daemon listening on ${server.url}`); } catch (error) { - io.err(`pi2d: ${errorMessage(error)}`); + io.err(`pi2: ${errorMessage(error)}`); lock?.release(); if (wired !== undefined) await wired.close().catch(() => undefined); return 1; @@ -233,7 +226,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { process.once(signal, () => { void shutdown(signal).catch((error: unknown) => { - io.err(`pi2d: shutdown failed: ${errorMessage(error)}`); + io.err(`pi2: shutdown failed: ${errorMessage(error)}`); process.exit(1); }); }); @@ -241,25 +234,3 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions return 0; } - -function isDirectRun(): boolean { - const entry = process.argv[1]; - if (entry === undefined) return false; - try { - return realpathOrSelf(entry) === realpathOrSelf(fileURLToPath(import.meta.url)); - } catch { - return false; - } -} - -if (isDirectRun()) { - void main(process.argv.slice(2)).then( - (code) => { - if (code !== 0) process.exitCode = code; - }, - (error: unknown) => { - process.stderr.write(`pi2d: ${errorMessage(error)}\n`); - process.exitCode = 1; - }, - ); -} diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index fca047e..a184ac5 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -149,7 +149,7 @@ export function checkRuntimeDir(probe: DoctorContext["runtime"]): DoctorCheck { export function checkCliToken(probe: DoctorContext["cliToken"]): DoctorCheck { if (!probe.exists) { - return { name: "cli-token", status: "warn", detail: `${probe.path} missing (start pi2d to mint it)` }; + return { name: "cli-token", status: "warn", detail: `${probe.path} missing (start the daemon with \`pi2 daemon\`)` }; } const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0; return { @@ -172,13 +172,13 @@ export function checkSocket(probe: DoctorContext["socket"], daemonReachable: boo export function checkDaemon(probe: DoctorContext["daemon"]): DoctorCheck { if (!probe.reachable) { - return { name: "daemon", status: "fail", detail: probe.error ?? "not reachable (is pi2d running?)" }; + return { name: "daemon", status: "fail", detail: probe.error ?? "not reachable (is the daemon running?)" }; } return { name: "daemon", status: "ok", detail: `http://127.0.0.1:${probe.port ?? "?"} reachable` }; } export function checkPort(probe: DoctorContext["port"]): DoctorCheck { - if (probe.bound) return { name: "port", status: "ok", detail: `${probe.configured} bound by pi2d` }; + if (probe.bound) return { name: "port", status: "ok", detail: `${probe.configured} bound by the daemon` }; return { name: "port", status: "ok", detail: `${probe.configured} free` }; } @@ -357,7 +357,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise void; removeFile?: (path: string) => void; runtime?: string; + /** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */ + daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise; } export async function main(argv: readonly string[], options: Pi2Options = {}): Promise { @@ -484,6 +489,13 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P try { switch (command) { + case "daemon": { + // `pi2 daemon` and `pi2 daemon start` are the same thing; the + // optional `start` word is consumed here so the daemon parser + // only ever sees flags. + const argv = rest[0] === "start" ? rest.slice(1) : rest; + return await (options.daemonMain ?? runDaemonMain)(argv, { out, err }); + } case "attach": { const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } }); if (boolFlag(parsed.flags, "--help")) { diff --git a/src/cli/service.ts b/src/cli/service.ts index 6b28460..9085adf 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -15,7 +15,7 @@ export type ServicePlatform = "linux" | "darwin"; export interface ServicePaths { /** Absolute node binary (`process.execPath`). */ nodePath: string; - /** Absolute path to `dist/cli/pi2d.js`. */ + /** Absolute path to `dist/cli/pi2.js`. */ scriptPath: string; /** Where logs go (plist StandardOut/ErrPath). */ stateDir: string; @@ -30,7 +30,7 @@ export interface ServicePaths { } export interface RenderedService { - /** `pi2d.service` on Linux, `com.pi2.pi2d.plist` on macOS. */ + /** `pi2.service` on Linux, `com.pi2.daemon.plist` on macOS. */ name: string; /** Absolute install path. */ path: string; @@ -41,13 +41,13 @@ export interface RenderedService { removeCommands: string[]; } -export const SYSTEMD_UNIT_NAME = "pi2d.service"; -export const LAUNCHD_LABEL = "com.pi2.pi2d"; +export const SYSTEMD_UNIT_NAME = "pi2.service"; +export const LAUNCHD_LABEL = "com.pi2.daemon"; export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`; -/** `/dist/cli/pi2d.js`, resolved from either `src/cli/` or `dist/cli/`. */ +/** `/dist/cli/pi2.js`, resolved from either `src/cli/` or `dist/cli/`. */ export function defaultScriptPath(): string { - return fileURLToPath(new URL("../../dist/cli/pi2d.js", import.meta.url)); + return fileURLToPath(new URL("../../dist/cli/pi2.js", import.meta.url)); } export function defaultServicePaths(overrides: Partial = {}): ServicePaths { @@ -96,12 +96,12 @@ export function renderSystemdUnit(paths: ServicePaths): string { const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`); return [ "[Unit]", - "Description=pi2 daemon (pi2d)", + "Description=pi2 daemon", "After=network.target", "", "[Service]", "Type=simple", - `ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} --foreground`, + `ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} daemon --foreground`, ...env, "Restart=on-failure", "RestartSec=2", @@ -139,6 +139,7 @@ export function renderLaunchAgent(paths: ServicePaths): string { " ", ` ${xmlEscape(paths.nodePath)}`, ` ${xmlEscape(paths.scriptPath)}`, + " daemon", " --foreground", " ", ...envBlock, @@ -147,9 +148,9 @@ export function renderLaunchAgent(paths: ServicePaths): string { " KeepAlive", " ", " StandardOutPath", - ` ${xmlEscape(join(paths.stateDir, "pi2d.log"))}`, + ` ${xmlEscape(join(paths.stateDir, "pi2-daemon.log"))}`, " StandardErrorPath", - ` ${xmlEscape(join(paths.stateDir, "pi2d.err.log"))}`, + ` ${xmlEscape(join(paths.stateDir, "pi2-daemon.err.log"))}`, "", "", "", diff --git a/src/cli/token.ts b/src/cli/token.ts index 7c96f25..766af30 100644 --- a/src/cli/token.ts +++ b/src/cli/token.ts @@ -1,10 +1,10 @@ /** * The local CLI token (`/cli.token`). * - * `pi2d` mints a fresh 32-byte hex token on every start and writes it 0600. + * `pi2 daemon` mints a fresh 32-byte hex token on every start and writes it 0600. * `AuthStore` accepts it as the synthetic `local-cli` admin device, so every * local `pi2*` command can talk to the daemon without pairing. The token is - * per-daemon-lifetime: restarting `pi2d` rotates it. + * per-daemon-lifetime: restarting `pi2 daemon` rotates it. */ import { randomBytes } from "node:crypto"; import { chmodSync, existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; diff --git a/src/cli/util.ts b/src/cli/util.ts index e4b47b3..b4c636f 100644 --- a/src/cli/util.ts +++ b/src/cli/util.ts @@ -1,4 +1,4 @@ -/** Small shared helpers for the `pi2` / `pi2d` command line front ends. */ +/** Small shared helpers for the `pi2` command line front end (and `pi2 daemon`). */ import { readFileSync, realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; diff --git a/src/cli/wiring.ts b/src/cli/wiring.ts index 88c245c..43815e9 100644 --- a/src/cli/wiring.ts +++ b/src/cli/wiring.ts @@ -1,5 +1,5 @@ /** - * Composition root: the real dependency graph behind `pi2d`. + * Composition root: the real dependency graph behind `pi2 daemon`. * * Everything the daemon serves is assembled here so that the CLI entry point * only has to deal with process concerns (args, lock, signals, daemon.json): diff --git a/src/config.ts b/src/config.ts index 3e4ff22..1102fbd 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2,7 +2,7 @@ * Daemon configuration. * * Defaults follow `docs/protocol.md`; deployment-specific values come from the - * environment so `pi2d` can be started without a config file. + * environment so `pi2 daemon` can be started without a config file. */ import { fileURLToPath } from "node:url"; import { daemonTokenPath, dataDir } from "./core/paths.js"; diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index a75996e..b2612ca 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -6,7 +6,7 @@ * - `src/daemon/**` W1 (HTTP/WS/SSE/auth/static/router) * - `src/instances/**` W2 (supervisor: one managed nvim per workspace) * - `src/workspaces/**` W3 (registry + disk discovery) - * - `src/cli/**` W8 (pi2d / pi2 commands) + * - `src/cli/**` W8 (pi2 / daemon commands) * * Do not change these shapes without updating `docs/protocol.md`. */ diff --git a/src/daemon/auth.ts b/src/daemon/auth.ts index 645fe97..3fcff2a 100644 --- a/src/daemon/auth.ts +++ b/src/daemon/auth.ts @@ -5,7 +5,7 @@ * is persisted, in `$PI2_DATA_DIR/devices.json` (mode 0600, atomic replace). * * A second, non-persisted credential exists for local tooling: the CLI token in - * `/cli.token` (written by `pi2d`). It authenticates as the synthetic + * `/cli.token` (written by `pi2 daemon`). It authenticates as the synthetic * `local-cli` device with every scope; see `docs/deployment.md` §7. */ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; @@ -67,7 +67,7 @@ export interface AuthStoreOptions { /** `touchDevice` write throttle. */ touchIntervalMs?: number; /** - * File holding the local CLI token (`/cli.token`, written by `pi2d`). + * File holding the local CLI token (`/cli.token`, written by `pi2 daemon`). * A bearer token equal to its trimmed contents authenticates as the synthetic * `local-cli` device with every scope. Checked after the persisted devices. */ diff --git a/test/cli/pi2d.test.ts b/test/cli/daemon.test.ts similarity index 92% rename from test/cli/pi2d.test.ts rename to test/cli/daemon.test.ts index 75636e1..b10da8e 100644 --- a/test/cli/pi2d.test.ts +++ b/test/cli/daemon.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; -import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/pi2d.js"; +import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/daemon.js"; import { acquireLock } from "../../src/cli/lock.js"; import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js"; import { UsageError } from "../../src/cli/util.js"; @@ -44,12 +44,13 @@ describe("parseDaemonArgs", () => { }); }); -describe("pi2d main (non-listening paths)", () => { +describe("daemon main (non-listening paths)", () => { it("prints usage for --help", async () => { const out: string[] = []; const code = await main(["--help"], { out: (line) => out.push(line), err: () => undefined }); expect(code).toBe(0); - expect(out.join("\n")).toContain("Usage: pi2d [options]"); + expect(out[0]?.split("\n")[0]).toBe("pi2 daemon — pi2 daemon"); + expect(out.join("\n")).toContain("Usage: pi2 daemon [start] [options]"); expect(out.join("\n")).toContain("--static-dir"); }); @@ -57,7 +58,7 @@ describe("pi2d main (non-listening paths)", () => { const out: string[] = []; const code = await main(["--version"], { out: (line) => out.push(line), err: () => undefined }); expect(code).toBe(0); - expect(out[0]).toMatch(/^pi2d \d+\.\d+\.\d+/); + expect(out[0]).toMatch(/^pi2 \d+\.\d+\.\d+/); }); it("exits 2 on bad arguments", async () => { @@ -112,12 +113,12 @@ describe("local CLI token", () => { }); }); -describe("pi2d singleton lock vs cli.token", () => { +describe("daemon singleton lock vs cli.token", () => { let dir: string; let tokenPath: string; beforeEach(() => { - dir = tempDir("pi2d-main-lock-"); + dir = tempDir("pi2-daemon-main-lock-"); setRuntimeEnv(dir); mkdirSync(join(dir, "web"), { recursive: true }); tokenPath = join(dir, "run", "cli.token"); @@ -147,7 +148,7 @@ describe("pi2d singleton lock vs cli.token", () => { const err: string[] = []; const code = await main([], { out: () => undefined, err: (line) => err.push(line) }); expect(code).toBe(1); - expect(err.join("\n")).toContain("another pi2d is running"); + expect(err.join("\n")).toContain("another pi2 daemon is running"); expect(readCliToken(tokenPath)).toBe(original); } finally { holder.release(); diff --git a/test/cli/helpers.ts b/test/cli/helpers.ts index 974ed98..d57bb12 100644 --- a/test/cli/helpers.ts +++ b/test/cli/helpers.ts @@ -11,7 +11,7 @@ export const TEST_LIMITS: Limits = { maxConnections: 64, }; -export function tempDir(prefix = "pi2d-cli-"): string { +export function tempDir(prefix = "pi2-daemon-cli-"): string { return mkdtempSync(join(tmpdir(), prefix)); } @@ -26,8 +26,8 @@ export function testConfig(overrides: Partial = {}): Config { staticDir: "/nonexistent-web-dist", corsOrigins: [], limits: TEST_LIMITS, - tokenPath: "/tmp/pi2d-cli-test.sock.token", - deviceStorePath: "/tmp/pi2d-cli-test-devices.json", + tokenPath: "/tmp/pi2-daemon-cli-test.sock.token", + deviceStorePath: "/tmp/pi2-daemon-cli-test-devices.json", }; return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; } diff --git a/test/cli/pi2.test.ts b/test/cli/pi2.test.ts index 125de39..7df8f26 100644 --- a/test/cli/pi2.test.ts +++ b/test/cli/pi2.test.ts @@ -140,7 +140,7 @@ describe("resolveEndpoint / createClient", () => { }); it("explains a missing daemon or token", () => { - expect(() => resolveEndpoint(dir)).toThrowError(/no running pi2d/); + expect(() => resolveEndpoint(dir)).toThrowError(/no running pi2 daemon/); writeDaemonJson(DAEMON, join(dir, "daemon.json")); expect(() => resolveEndpoint(dir)).toThrowError(/missing CLI token/); }); @@ -149,7 +149,7 @@ describe("resolveEndpoint / createClient", () => { writeDaemonJson({ ...DAEMON, port: 1 }, join(dir, "daemon.json")); writeCliToken(join(dir, "cli.token")); const client = createClient({ endpoint: resolveEndpoint(dir), timeoutMs: 500 }); - await expect(client.get("/api/v1/info")).rejects.toThrowError(/cannot reach pi2d/); + await expect(client.get("/api/v1/info")).rejects.toThrowError(/cannot reach the pi2 daemon/); }); }); @@ -255,11 +255,11 @@ describe("pi2 attach", () => { exec: recorded.exec, warn: (line) => warnings.push(line), client: () => { - throw new CliError("no running pi2d (daemon.json missing)"); + throw new CliError("no running pi2 daemon (daemon.json missing)"); }, }); expect(code).toBe(0); - expect(warnings[0]).toContain("no running pi2d"); + expect(warnings[0]).toContain("no running pi2 daemon"); expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); }); @@ -274,12 +274,12 @@ describe("pi2 attach", () => { client: () => { const client = fakeClient(); client.get = async () => { - throw new CliError("cannot reach pi2d"); + throw new CliError("cannot reach the pi2 daemon"); }; return client; }, }); - expect(warnings[0]).toContain("cannot reach pi2d"); + expect(warnings[0]).toContain("cannot reach the pi2 daemon"); expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); }); }); @@ -362,18 +362,18 @@ describe("pi2 doctor (daemon probe wiring)", () => { expect(daemon?.status).toBe("ok"); expect(daemon?.detail).toContain("http://127.0.0.1:7712"); expect(report.checks.find((check) => check.name === "protocol")?.status).toBe("ok"); - expect(report.checks.find((check) => check.name === "port")?.detail).toBe("7712 bound by pi2d"); + expect(report.checks.find((check) => check.name === "port")?.detail).toBe("7712 bound by the daemon"); }); it("reports an unreachable daemon without throwing", async () => { const report = await runDoctorCommand({ client: () => { - throw new CliError("no running pi2d (daemon.json missing)"); + throw new CliError("no running pi2 daemon (daemon.json missing)"); }, }); const daemon = report.checks.find((check) => check.name === "daemon"); expect(daemon?.status).toBe("fail"); - expect(daemon?.detail).toContain("no running pi2d"); + expect(daemon?.detail).toContain("no running pi2 daemon"); expect(report.ok).toBe(false); }); }); @@ -411,11 +411,11 @@ describe("pi2 main", () => { const code = await main(["status"], { err: (line) => err.push(line), client: () => { - throw new CliError("no running pi2d"); + throw new CliError("no running pi2 daemon"); }, }); expect(code).toBe(1); - expect(err[0]).toBe("pi2: no running pi2d"); + expect(err[0]).toBe("pi2: no running pi2 daemon"); }); it("routes attach through runAttach with an injected exec", async () => { @@ -430,6 +430,45 @@ describe("pi2 main", () => { expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd: process.cwd() }]); }); + it("dispatches `daemon` to the daemon entry point", async () => { + const out: string[] = []; + const err: string[] = []; + const seen: string[][] = []; + const code = await main(["daemon", "--help"], { + out: (line) => out.push(line), + err: (line) => err.push(line), + daemonMain: async (argv, io) => { + seen.push([...argv]); + io.out("daemon usage"); + io.err("daemon warning"); + return 7; + }, + }); + expect(code).toBe(7); + expect(seen).toEqual([["--help"]]); + expect(out).toEqual(["daemon usage"]); + expect(err).toEqual(["daemon warning"]); + }); + + it("strips the optional `start` word before parsing daemon flags", async () => { + const seen: string[][] = []; + const code = await main(["daemon", "start", "--help"], { + daemonMain: async (argv) => { + seen.push([...argv]); + return 0; + }, + }); + expect(code).toBe(0); + expect(seen).toEqual([["--help"]]); + }); + + it("exits 2 on an unknown daemon subcommand", async () => { + const err: string[] = []; + const code = await main(["daemon", "bogus"], { out: () => undefined, err: (line) => err.push(line) }); + expect(code).toBe(2); + expect(err.join("\n")).toContain("unexpected argument bogus"); + }); + it("installs a service with --write through the injected writer", async () => { const out: string[] = []; const writes: { path: string; content: string }[] = []; @@ -438,7 +477,7 @@ describe("pi2 main", () => { platform: "linux", servicePaths: { nodePath: "/usr/bin/node", - scriptPath: "/repo/dist/cli/pi2d.js", + scriptPath: "/repo/dist/cli/pi2.js", stateDir: "/state", homeDir: "/home/u", pathEnv: "/usr/bin", @@ -446,9 +485,9 @@ describe("pi2 main", () => { writeFile: (path, content) => writes.push({ path, content }), }); expect(code).toBe(0); - expect(writes[0]?.path).toBe(join("/home/u/.config/systemd/user", "pi2d.service")); - expect(writes[0]?.content).toContain("ExecStart=/usr/bin/node /repo/dist/cli/pi2d.js --foreground"); - expect(out.join("\n")).toContain("systemctl --user enable --now pi2d.service"); + expect(writes[0]?.path).toBe(join("/home/u/.config/systemd/user", "pi2.service")); + expect(writes[0]?.content).toContain("ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground"); + expect(out.join("\n")).toContain("systemctl --user enable --now pi2.service"); }); it("prints the service on the default dry-run", async () => { @@ -458,7 +497,7 @@ describe("pi2 main", () => { platform: "darwin", servicePaths: { nodePath: "/usr/bin/node", - scriptPath: "/repo/dist/cli/pi2d.js", + scriptPath: "/repo/dist/cli/pi2.js", stateDir: "/state", homeDir: "/home/u", pathEnv: "/usr/bin", @@ -466,7 +505,7 @@ describe("pi2 main", () => { }); expect(code).toBe(0); expect(out.join("\n")).toContain("KeepAlive"); - expect(out.join("\n")).toContain("would write /home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); + expect(out.join("\n")).toContain("would write /home/u/Library/LaunchAgents/com.pi2.daemon.plist"); }); it("renders doctor output and exits 1 when a check fails", async () => { diff --git a/test/cli/service.test.ts b/test/cli/service.test.ts index 4876ae4..8ab90f8 100644 --- a/test/cli/service.test.ts +++ b/test/cli/service.test.ts @@ -14,19 +14,19 @@ import { runInstallService, runUninstallService } from "../../src/cli/pi2.js"; const paths: ServicePaths = { nodePath: "/opt/node/bin/node", - scriptPath: "/repo/dist/cli/pi2d.js", + scriptPath: "/repo/dist/cli/pi2.js", stateDir: "/home/u/.local/state/pi2", homeDir: "/home/u", pathEnv: "/opt/node/bin:/usr/bin:/bin", }; const LINUX_UNIT = `[Unit] -Description=pi2 daemon (pi2d) +Description=pi2 daemon After=network.target [Service] Type=simple -ExecStart=/opt/node/bin/node /repo/dist/cli/pi2d.js --foreground +ExecStart=/opt/node/bin/node /repo/dist/cli/pi2.js daemon --foreground Environment=PATH=/opt/node/bin:/usr/bin:/bin Restart=on-failure RestartSec=2 @@ -42,11 +42,12 @@ const MAC_PLIST = ` Label - com.pi2.pi2d + com.pi2.daemon ProgramArguments /opt/node/bin/node - /repo/dist/cli/pi2d.js + /repo/dist/cli/pi2.js + daemon --foreground EnvironmentVariables @@ -59,9 +60,9 @@ const MAC_PLIST = ` KeepAlive StandardOutPath - /home/u/.local/state/pi2/pi2d.log + /home/u/.local/state/pi2/pi2-daemon.log StandardErrorPath - /home/u/.local/state/pi2/pi2d.err.log + /home/u/.local/state/pi2/pi2-daemon.err.log `; @@ -80,22 +81,22 @@ describe("systemd user unit", () => { }); it("quotes values with spaces", () => { - const unit = renderSystemdUnit({ ...paths, scriptPath: "/repo dir/cli/pi2d.js" }); - expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2d.js" --foreground'); + const unit = renderSystemdUnit({ ...paths, scriptPath: "/repo dir/cli/pi2.js" }); + expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2.js" daemon --foreground'); }); it("targets ~/.config/systemd/user and honours XDG_CONFIG_HOME", () => { expect(systemdUserDir(paths)).toBe("/home/u/.config/systemd/user"); expect(systemdUserDir({ ...paths, configHome: "/xdg" })).toBe("/xdg/systemd/user"); const service = renderService("linux", paths); - expect(service.path).toBe("/home/u/.config/systemd/user/pi2d.service"); - expect(service.name).toBe("pi2d.service"); + expect(service.path).toBe("/home/u/.config/systemd/user/pi2.service"); + expect(service.name).toBe("pi2.service"); expect(serviceDir(service)).toBe("/home/u/.config/systemd/user"); expect(service.commands).toEqual([ "systemctl --user daemon-reload", - "systemctl --user enable --now pi2d.service", + "systemctl --user enable --now pi2.service", ]); - expect(service.removeCommands).toContain("systemctl --user disable --now pi2d.service"); + expect(service.removeCommands).toContain("systemctl --user disable --now pi2.service"); }); }); @@ -112,14 +113,14 @@ describe("LaunchAgent plist", () => { it("targets ~/Library/LaunchAgents", () => { expect(launchAgentDir(paths)).toBe("/home/u/Library/LaunchAgents"); const service = renderService("darwin", paths); - expect(service.path).toBe("/home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); - expect(service.name).toBe("com.pi2.pi2d.plist"); + expect(service.path).toBe("/home/u/Library/LaunchAgents/com.pi2.daemon.plist"); + expect(service.name).toBe("com.pi2.daemon.plist"); expect(service.commands[0]).toContain("launchctl bootstrap gui/$(id -u)"); expect(service.removeCommands[0]).toContain("launchctl bootout"); }); - it("resolves dist/cli/pi2d.js next to the built CLI", () => { - expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2d\.js$/); + it("resolves dist/cli/pi2.js next to the built CLI", () => { + expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2\.js$/); }); }); @@ -137,8 +138,8 @@ describe("install-service / uninstall-service commands", () => { expect(code).toBe(0); expect(writes).toEqual([]); expect(lines.join("\n")).toContain("[Service]"); - expect(lines.join("\n")).toContain("would write /home/u/.config/systemd/user/pi2d.service"); - expect(lines.join("\n")).toContain("systemctl --user enable --now pi2d.service"); + expect(lines.join("\n")).toContain("would write /home/u/.config/systemd/user/pi2.service"); + expect(lines.join("\n")).toContain("systemctl --user enable --now pi2.service"); }); it("writes the unit on --write and prints the enable commands", () => { @@ -152,8 +153,8 @@ describe("install-service / uninstall-service commands", () => { writeFile: (path, content) => writes.push({ path, content }), }); expect(code).toBe(0); - expect(writes).toEqual([{ path: join("/home/u/.config/systemd/user", "pi2d.service"), content: LINUX_UNIT }]); - expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2d.service (mode 0644)"); + expect(writes).toEqual([{ path: join("/home/u/.config/systemd/user", "pi2.service"), content: LINUX_UNIT }]); + expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2.service (mode 0644)"); expect(lines.join("\n")).toContain("systemctl --user daemon-reload"); }); @@ -170,7 +171,7 @@ describe("install-service / uninstall-service commands", () => { }), ).toBe(0); expect(removed).toEqual([]); - expect(dry.join("\n")).toContain("would remove /home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); + expect(dry.join("\n")).toContain("would remove /home/u/Library/LaunchAgents/com.pi2.daemon.plist"); const lines: string[] = []; expect( @@ -182,7 +183,7 @@ describe("install-service / uninstall-service commands", () => { removeFile: (path) => removed.push(path), }), ).toBe(0); - expect(removed).toEqual(["/home/u/Library/LaunchAgents/com.pi2.pi2d.plist"]); + expect(removed).toEqual(["/home/u/Library/LaunchAgents/com.pi2.daemon.plist"]); expect(lines.join("\n")).toContain("launchctl bootout"); }); }); diff --git a/test/daemon/harness.ts b/test/daemon/harness.ts index 3445fdf..9cd5f04 100644 --- a/test/daemon/harness.ts +++ b/test/daemon/harness.ts @@ -13,7 +13,7 @@ export const TEST_LIMITS: Limits = { maxConnections: 64, }; -export function tempDir(prefix = "pi2d-test-"): string { +export function tempDir(prefix = "pi2-daemon-test-"): string { return mkdtempSync(join(tmpdir(), prefix)); } @@ -24,8 +24,8 @@ export function testConfig(overrides: Partial = {}): Config { staticDir: "/nonexistent-web-dist", corsOrigins: [], limits: TEST_LIMITS, - tokenPath: "/tmp/pi2d-test.sock.token", - deviceStorePath: "/tmp/pi2d-test-devices.json", + tokenPath: "/tmp/pi2-daemon-test.sock.token", + deviceStorePath: "/tmp/pi2-daemon-test-devices.json", }; return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; } diff --git a/test/instances/helpers.ts b/test/instances/helpers.ts index 147586d..6e57343 100644 --- a/test/instances/helpers.ts +++ b/test/instances/helpers.ts @@ -33,7 +33,7 @@ export interface TempEnv { const ENV_KEYS = ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_NVIM_BIN", "PI2_NVIM_INIT"] as const; -export function makeTempEnv(prefix = "pi2d-instances-"): TempEnv { +export function makeTempEnv(prefix = "pi2-daemon-instances-"): TempEnv { const dir = mkdtempSync(join(tmpdir(), prefix)); const runtime = join(dir, "run"); const data = join(dir, "data"); diff --git a/test/workspaces/discovery.test.ts b/test/workspaces/discovery.test.ts index 9dd9d18..18ad82f 100644 --- a/test/workspaces/discovery.test.ts +++ b/test/workspaces/discovery.test.ts @@ -10,7 +10,7 @@ describe("workspace disk discovery", () => { let root: string; beforeEach(() => { - sandbox = makeSandbox("pi2d-discovery-"); + sandbox = makeSandbox("pi2-daemon-discovery-"); root = join(sandbox, "agent", "sessions"); mkdirSync(root, { recursive: true }); }); diff --git a/test/workspaces/helpers.ts b/test/workspaces/helpers.ts index 62af38d..cf4c21b 100644 --- a/test/workspaces/helpers.ts +++ b/test/workspaces/helpers.ts @@ -15,7 +15,7 @@ export interface SessionSpec { mtime?: Date | number; } -export function makeSandbox(prefix = "pi2d-ws-"): string { +export function makeSandbox(prefix = "pi2-daemon-ws-"): string { return mkdtempSync(join(tmpdir(), prefix)); } diff --git a/test/workspaces/registry.test.ts b/test/workspaces/registry.test.ts index 5584e6b..f8dbbce 100644 --- a/test/workspaces/registry.test.ts +++ b/test/workspaces/registry.test.ts @@ -11,7 +11,7 @@ describe("workspace registry", () => { let project: string; beforeEach(() => { - sandbox = makeSandbox("pi2d-registry-"); + sandbox = makeSandbox("pi2-daemon-registry-"); file = join(sandbox, "data", "workspaces.json"); project = join(sandbox, "project"); mkdirSync(project, { recursive: true }); diff --git a/test/workspaces/store.test.ts b/test/workspaces/store.test.ts index 5038851..e5f5b36 100644 --- a/test/workspaces/store.test.ts +++ b/test/workspaces/store.test.ts @@ -43,7 +43,7 @@ describe("workspace store", () => { let projectGhost: string; beforeEach(() => { - sandbox = makeSandbox("pi2d-store-"); + sandbox = makeSandbox("pi2-daemon-store-"); sessions = join(sandbox, "agent", "sessions"); dataFile = join(sandbox, "data", "workspaces.json"); allowRoot = join(sandbox, "code"); diff --git a/web/tests/chat.reducer.test.tsx b/web/tests/chat.reducer.test.tsx index 0378bb4..7d2697a 100644 --- a/web/tests/chat.reducer.test.tsx +++ b/web/tests/chat.reducer.test.tsx @@ -200,7 +200,7 @@ describe("canonical reducer integration", () => { expect(state.flags.attention).toBe(false); }); - it("replays the pi2d basic-turn fixture through the shared reducer", () => { + it("replays the basic-turn fixture through the shared reducer", () => { const fixture = join(process.cwd(), "..", "fixtures", "basic-turn", "events.jsonl"); if (!existsSync(fixture)) { expect(true).toBe(true);