30 Commits
Author SHA1 Message Date
yuez 32292873f9 feat(daemon): serve a live-only prompt-history read
The web composer's ↑/↓ recall needs the plugin's prompt history, so the browser
and nvim walk one list instead of two. The daemon relays it and stores nothing:
it is a router, and the plugin stays the authority (AGENTS.md rule 2).

- plugin `hello` advertises the new `promptHistory` capability; the daemon never
  relays the read to a plugin that did not advertise it
- `workspace.query{kind:"promptHistory",limit}` is answered by the plugin from
  its own `prompt.history` archive (workspace cwd), oldest-first
- `GET /api/v1/workspaces/:id/prompt-history?limit=` → `{v, workspaceId, live,
  supported, entries}`; `limit` defaults to 200 and clamps to 500, an unknown
  workspace is a 404, and malformed entries are dropped
- the read deliberately does **not** call `instances.ensure()`: recall is a
  keystroke, not a lifecycle event, so a workspace with no connected plugin
  answers `{live:false, supported:false, entries:[]}` instead of booting an nvim
- `PluginConnection.capabilities` joins the interface the daemon sees, and the
  fake connection grows a writable one so the gate is testable

No event or reducer change: `fixtures/` are untouched.
2026-11-02 11:12:21 +08:00
yuez 2f2f1bb518 feat(daemon): report host uptime, not only the daemon's process age
The status tile labelled "uptime" showed the age of the daemon *process*
(`/info.uptimeMs`), and `/info` was fetched once with a 30 s staleTime and no
refetch interval, so the figure also froze: on a box five days up, a
`pi2 update` restart made the tile read "3m" and it never moved again.

`os.uptime()` is now sampled with the other host figures and served as
`system.hostUptimeSec` — which the 3 s `/resources` poll already refreshes —
plus an additive `/info.hostUptimeMs`. The tile renders it through a
`LiveUptime` label that anchors the reported snapshot once and ticks locally,
so the counter advances without a refetch and cannot rewind on a re-render.
The daemon's own process age stays in the server card, relabelled
`status.daemonUptime`, next to the `pid`/`daemonId` that give it meaning.
2026-10-30 16:18:48 +08:00
yuez 01fd7b9922 fix(daemon): sample disk usage on the filesystems pi2d uses
The status tile read `—` on a fresh machine: the sampler ran `statfs` on the
daemon's state dir, which is created lazily on the first instance log, so the
call failed with ENOENT and `diskUsedBytes`/`diskTotalBytes`/`diskPercent` all
came back null — `/info` then dropped `disk` altogether and the failure was
indistinguishable from a full disk.

`probeMount()` now walks up to the nearest existing ancestor and then to the
filesystem boundary (`st_dev` change), so a sample describes a volume, not a
directory. Candidates are pi2d's own write targets — `/` (the home volume on
macOS, where `/` is the sealed read-only system volume), the pi session store
and the visible workspace roots — never a mount-table dump: an unrelated or
hung network mount must not stall the sampler. Rows are deduped by `st_dev`,
sorted most-constrained first, capped at four, and reported as `system.disks[]`
with the legacy scalars aliasing the worst row. A sample that yields nothing
now carries `diskError` instead of silent nulls.

The status tile shows the worst filesystem and, when several are in play, one
quiet row per mount instead of a single percentage that hides the full volume.
2026-10-30 16:17:43 +08:00
yuez 17fcf931c0 feat(workspaces): title recent-activity rows from a bounded preview
The activity column's disk-only rows had no title: the recent feed carried file
metadata only, so every session outside a live instance rendered "(unnamed)".

recentSessions() now projects a display title for the rows it returns — the
latest `session_info` name and the first user message — from a 128 KiB head +
32 KiB tail of each session file, cached by (mtime, size). Entries are never
parsed into session state: the read is bounded, opt-in, and only paid for the
≤limit rows the caller renders, so the daemon stays a router.

The web client keeps the disk title as a fallback under the live state, and the
B4 e2e scenario asserts session-first rows with their links and titles.
2026-10-30 15:15:09 +08:00
yuez 2240289426 feat(cli): add pi2 uninstall for cross-channel state cleanup
`install.sh --uninstall`, `brew uninstall`, `npm rm -g` and
`pi2 uninstall-service` each own one slice; none of them removed the
runtime directory, and deleting the binary left a running daemon behind.

`pi2 uninstall` now owns the state for every channel: disable and remove
the unit, stop the daemon, delete the runtime dir, and — with `--purge` /
`--purge-config` — the data, state and env file. On the curl channel
`--purge` also deletes the install tree, last, because the running binary
lives inside it; npm/brew/AUR trees stay with their package manager, and
the command to remove them is printed instead.

Destructive by design: the plan is always printed, `--yes` (or an
interactive `y`) is required, non-TTY runs refuse without it, and
everything a reinstall would silently lose is an explicit opt-in. The
next-steps footer names what no CLI can clean: the browser's site data and
the plugin-private copy from `:PiWebInstall`.

Docs: rewrite the install.md uninstall section around the two layers
(state vs. binaries) with a table of every path, point deployment.md at
the new command, and update the README.
2026-10-30 09:40:05 +08:00
yuez 8fb535f7f3 feat(cli): add pi2 update with a versioned install layout
The standalone (curl installer) channel had no upgrade path of its own: the
documented one was 're-run the installer', which the Neovim plugin cannot do
safely and which re-downloads 35 MB without version arithmetic, provenance or
rollback. ADR 0003 records the design; this is the implementation.

- install.sh now installs one immutable tree per version
  (`<prefix>/versions/<v>/{bin,share,LICENSE}`) behind a single atomically
  swapped `current` symlink, writes `<prefix>/install.json` as the install
  receipt, and migrates a pre-0.1.7 flat layout in place. Keeping `current` plus
  one previous tree gives a one-step rollback for free.
- `pi2 update` (native TypeScript, no `curl | sh` subprocess) resolves the
  release with an ETag-cached GitHub lookup, picks the asset from the
  build-time `PI2_BUILD_TARGET` define instead of re-probing libc, verifies
  SHA256SUMS, verifies SLSA provenance with `gh attestation verify`, runs the
  new binary once, then swaps `current` and rewrites the receipt. Flags:
  --check/--dry-run/--version/--force/--json/--require-attestation/
  --skip-attestation. Downgrades need --force; restarts stay manual.
- the receipt is the only channel detection: npm, Homebrew and the AUR are
  refused with the command that owns their tree, and a flat install is told to
  re-run the installer once. No heuristics on `process.execPath`.
- `pi2 install-service` renders `<prefix>/current/bin/pi2`, so an update no
  longer invalidates the unit.
- `scripts/build-binary.sh` injects `PI2_BUILD_TARGET`; `tarball.ts` is a
  dependency-free ustar/PAX reader with traversal and symlink rejection.

Verified against the real release: install.sh into a scratch prefix, update
--check/--dry-run, a local 0.1.7 mirror upgrade (attestation warn path), then
`pi2 update --version 0.1.6 --force` (real download, real attestation
verified), plus boot-check and the refusal paths. typecheck + 567 daemon tests
+ web typecheck + 537 web tests + smoke are green.
2026-10-29 16:42:57 +08:00
yuez 8a39e65def feat(cli): add --json to pi2 pairing
The Neovim plugin needs the mint payload (URL, code, expiry, QR matrix, every
advertised base) to draw a scannable code, but the CLI only printed a human
report — so `:PiWebPair` spoke HTTP itself, duplicating the CLI token handling
and requiring `curl` in the editor.

`pi2 pairing --json` prints the normalised payload instead:

  { url, code, expiresAt?, qr: { version, ecc, mask, size, rows }, bases[] }

Same fields the human report renders, so the terminal QR and the float always
agree, and `--base` still pins the link.
2026-10-29 14:11:10 +08:00
yuez 4eda2b9420 feat(cli): add pi2 service status|start|stop|enable|disable
`install-service` only renders the unit file; nothing in the CLI talked to
systemd/launchd. The editor plugin had no supported way to start a
service-managed daemon (it would have had to shell out to `systemctl` itself),
so add the explicit control surface ADR 0002 §2.2 assumes:

  pi2 service status [--json]   manager, unit path, installed/enabled/active, linger
  pi2 service start|stop        systemctl --user start|stop / launchctl kickstart|kill
  pi2 service enable|disable    systemctl --user enable|disable --now / launchctl bootstrap|bootout

`status` never fails: no manager, no unit and a dead service are reports, and
`--json` carries the same shape the plugin decodes. The four mutating actions
exit 1 with the manager's first stderr line, and refuse to run when the unit
file is missing. Every probe is injectable (exec/exists/platform/paths/uid/user)
so the tests never touch a real service manager.
2026-10-29 14:00:41 +08:00
yuez b95ff6055b feat(cli): tell users when pi2.nvim cannot host a spawned instance
`checkPlugin` only looked for `lua/pi/web/bridge.lua`, so a checkout that can
drive an existing nvim but cannot be spawned reported `ok` and the failure
surfaced later as an unexplained "did not say hello".

The probe now also requires `lua/pi/host.lua`: both present is `ok`, bridge only
is `warn` with the update hint, neither is `fail`. `pi2 daemon --help` lists the
instance knobs (`PI2_NVIM_BIN`, `PI2_NVIM_INIT`, `PI2_PLUGIN_DIR`,
`PI2_ENSURE_TIMEOUT_MS`) it previously kept to itself.
2026-10-28 17:32:41 +08:00
yuez 85faacb0ba feat(workspaces): accept ~ paths and name as alias in workspace.add
The console's open dialog advertises `~/Workspace/...` and sends `name`, but the
daemon only accepted an absolute `cwd` and only read `alias`, so the most likely
first action failed with a generic `E_BAD_REQUEST` and the typed name vanished.

`add()` now expands `~`/`~/…` against the store's home before the absolute-path
check (a leading `~user` stays an error, and the message names both accepted
forms), and `workspace.add` treats `name` as an alias when `alias` is absent,
answering `workspaceId` so a client does not need a follow-up list call.

feat(cli): tell users when pi2.nvim cannot host a spawned instance

`checkPlugin` only looked for `lua/pi/web/bridge.lua`, so a checkout that can
drive an existing nvim but cannot be spawned reported `ok` and the failure
surfaced later as an unexplained "did not say hello".

The probe now also requires `lua/pi/host.lua`: both present is `ok`, bridge only
is `warn` with the update hint, neither is `fail`. `pi2 daemon --help` lists the
instance knobs (`PI2_NVIM_BIN`, `PI2_NVIM_INIT`, `PI2_PLUGIN_DIR`,
`PI2_ENSURE_TIMEOUT_MS`) it previously kept to itself.
MSG2
2026-10-28 17:32:23 +08:00
yuez db387ae248 feat(instances): spawn a host-capable nvim without the user's config
Opening a project from the console needed `:PiWebStart` first because the
managed spawn loaded the *user's* nvim config and ran with `stdio:"ignore"`.
When that config did not resolve pi2.nvim (lazy.nvim, a dev worktree behind
`PI_DEV_DIR`, a service with a frozen PATH) or the checkout lacked
`lua/pi/host.lua`, nvim stayed alive and silent and `instance.ensure` could only
report a bare 5 s timeout: nothing to read, nothing to fix.

- `core/plugin`: discover the plugin (`PI2_PLUGIN_DIR`, lazy.nvim,
  `site/pack/*/{start,opt}`, system dirs) and require both `lua/pi/host.lua` and
  `lua/pi/web/bridge.lua`; name a misconfigured `PI2_PLUGIN_DIR` first.
- `instances/host-init`: generate a minimal init (prepend the plugin, prepend
  nothing else, `cquit 1` when `pi.host` is missing) so a spawn fails with a real
  exit code instead of silence. `PI2_NVIM_INIT` keeps `user` (the old
  behaviour) and any explicit path.
- supervisor: refuse to spawn when no host-capable plugin exists, route the
  child's stdout/stderr into `instances/<id>.log`, and fold the log tail into
  `instance_state.reason` and the thrown error. `PI2_ENSURE_TIMEOUT_MS`
  (default 10000) replaces the fixed 5 s.
- `core/paths`: one shared `expandTilde` for the plugin probe, the workspace
  allowlist and `pi2 doctor`.
2026-10-28 17:32:16 +08:00
yuez d2e20d428a feat: session-first workspace activity and installable daemon
Workspaces page:
- list the newest sessions across workspaces in the activity column; the
  daemon exposes GET /api/v1/sessions/recent as a disk projection and the
  browser enriches live rows from the per-workspace session relay
- put recent activity first below 1100px and fix the mobile page-header
  flex-basis gap

Smoke:
- pin PI2_HOST=127.0.0.1 in both smoke scripts and make the startup-line
  assertion follow the configured host; the daemon default stays 0.0.0.0

Install:
- standalone binary build/install scripts, packaging templates, CI/release
  hooks, CLI-first install docs and the supporting config/doctor changes
2026-10-28 10:53:48 +08:00
yuez 22de7dcc9c feat(daemon): resolve /api/v1/models without spawning an instance
`GET /api/v1/models?workspaceId=` could only answer for a named workspace, and
naming one is enough to spawn its Neovim — fine for the chat picker, wrong for
the status page, which has no session to offer and would sit in
E_INSTANCE_STARTING forever.

The parameter is now optional. With one, the read is relayed exactly as before.
Without one, src/daemon/models.ts scans only instances that are already `ready`,
prefers the one with live sessions and the longest uptime, and relays
`workspace.query{kind:"models"}` to it, falling through to the next candidate on
failure. No instance is ever created.

The plugin's answer is lazy: the first call returns
`{providers:[], pending:true}` while its cache fills. The response therefore
carries `pending`, the `workspaceId` that answered (or null) and a
`pendingReason` of `fetching`, `no-instance` or `no-live-session`, so a client
can poll with a bound and explain itself instead of showing an empty list. The
workspaceId-scoped answer now also echoes `workspaceId` back.
2026-10-28 08:14:05 +08:00
yuez 88354ec078 feat(daemon): sample host cpu, memory and disk for /info and /resources
The status page had no host figures: `/api/v1/info` only carried identity and
`/api/v1/resources` only carried instance RSS, so the CPU/mem/disk tiles fell
back to "—" and the memory tile faked its percentage from RSS over physical
memory.

src/core/sysinfo.ts is a zero-dependency sampler: CPU from the /proc/stat delta
(null on the first read, since it needs two samples), load average from
os.loadavg(), memory from os.freemem/os.totalmem, and disk via statfs on the
daemon's state dir. One sample is cached for ~1 s and shared between /info and
/resources, so polling both does not double the syscalls. /info gains additive
`cpu`, `mem`, `disk` percentages plus `cpuCores` and `loadAvg`; /resources gains
a `system` object with the byte counts, the disk path and `sampledAt`.

Every field is optional on the client side: an older daemon simply omits them.
2026-10-28 08:13:58 +08:00
yuez 48411dccd2 feat(cli): add stop command to shut down running daemon 2026-10-27 18:37:21 +08:00
yuez e910e75849 feat: session-scoped entries query, session title tree and message stream updates 2026-10-27 17:30:28 +08:00
yuez 12adddf803 test(instances): increase timeout in silent instance test to avoid flakes 2026-10-27 14:20:40 +08:00
yuez a57c874095 feat(daemon)!: phone-first binding and a two-step pairing flow
Implements ADR 0001 (docs/adr/0001-phone-first-pairing.md): the console is
meant to be opened from a phone, so reachability stops being a mode and the
pairing link becomes the only access control that matters.

Binding / CORS
- `PI2_HOST` defaults to `0.0.0.0`; `PI2_ACCESS_MODE` (local|lan|tailscale) is
  deleted, together with its parser, `AccessMode` type and LAN probe.
- `src/core/network.ts` is the single source of truth for reachable addresses:
  kind classification, ordering (public → lan → other → tailscale → loopback,
  physical NICs first, link-local skipped), bind-aware `networkBases()`,
  `primaryBase()` and `localOrigins()`. Config, the pairing route, doctor and
  the CLI all consume it, so the CORS allowlist always matches the pairing URL.
- `/api/v1/info` and `daemon.json` report `host` instead of `access`; doctor's
  `access` check becomes `bind` (loopback ok, wildcard warns unless an `https:`
  public URL is configured).

Pairing
- `POST /api/v1/pair` only mints, requires a token, and returns the code, the
  chosen URL, the expiry, the nonce, the QR matrix and every usable base.
  `base` may pin one of those bases; anything else is a 400.
- `POST /api/v1/pair/redeem` is the public half, rate limited per client
  (5/min) and globally (50/h) → 429 `E_RATE_LIMITED` with `retry-after`.
- `GET /pair/:code` answers 302 to `/connect?code=…&auto=1`, so a scanned link
  needs no JavaScript to reach the console.
- `src/core/qr.ts` (moved out of the CLI) is the one encoder: byte mode, EC
  level M, versions 1–10, rows without a quiet zone, shared by the HTTP mint
  response and the terminal renderer.
- `pi2 pairing` prints a human report plus a half-block terminal QR and keeps
  `--base`; `--json` and `--public-url` are gone (the Neovim client calls the
  HTTP mint directly).

Device scopes
- `Scope`, `SCOPES`, `DEFAULT_SCOPES`, `DeviceRecord.scopes` and the `scopes`
  field in device/hello payloads are removed: nothing enforced them, and a
  paired device now holds the same rights as the local browser. A permission
  model, if wanted, gets its own ADR.

Breaking: `PI2_ACCESS_MODE`, `info.access`, `pi2 status --json`'s `access`,
`pi2 pairing --json`/`--public-url`, `POST /api/v1/pair {code}`, and the
`scopes` field. All in-repo callers and the e2e drivers are updated; the plugin
side (`:PiWebAccess`, `env.PI2_ACCESS_MODE`, text-format parsing) follows in
pi2.nvim.

Verification: root typecheck clean; 369/370 tests (the one failure is the
pre-existing supervisor timing flake, 24/24 in isolation ×3); `smoke.sh` green;
web suite 299/299; visual matrix 24/24.
2026-10-27 10:44:08 +08:00
yuez 0193230cd3 feat(cli): flag a missing curl in pi2 doctor
`:PiWeb` signs the local browser in through curl (Neovim has no HTTP client), so
a missing binary breaks the primary onboarding path. The new `curl` check sits
with the other binary probes, warns instead of failing, and can never flip
`doctor`'s exit code.
2026-10-23 10:08:15 +08:00
yuez 64a1a98c1f feat(daemon): collapse workspace noise into a "show hidden" section
Discovery returns every pi session directory ever seen, so the console opened on
47 rows on this machine: 20 ghosts (cwd deleted) and 21 scratch dirs under /tmp
next to the real projects. Every row now carries a derived, non-persisted
`visibility`/`visibilityReason`; nothing is filtered server-side, so
`/workspace/<id>` deep links and the chat page's id lookup still resolve.

Precedence: explicit `hidden` wins; a live instance, `pinned` or `trusted`
rescues a row; then temp paths (`PI2_WORKSPACE_HIDE_TEMP`, on), ghosts
(`PI2_WORKSPACE_HIDE_GHOSTS`, on), outside roots (`PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS`,
off) and staleness (`PI2_WORKSPACE_STALE_DAYS`, off). Measured on real data:
47 → 26 default rows, 0 openable rows lost.

The browser collapses the secondary rows behind a persisted toggle and dims them
with a reason badge; `workspace.add` now clears `hidden`.
2026-10-23 10:08:15 +08:00
yuez 9ab0830223 feat(cli): add pi2 open, pi2 pairing --public-url and the access check
`pi2 open [--print] [--no-browser]` mints a loopback browser session and hands
the URL to the platform opener without waiting for it, so "open the console" is
one command that never hangs. `pi2 pairing --public-url` (or `daemon.json.publicUrl`
/ `PI2_PUBLIC_URL`) rebuilds the printed URL and QR payload for a tailnet or
reverse-proxy base.

`pi2 doctor` gains an `access` check: ok on loopback, warn for `lan`/`tailscale`,
fail when a non-loopback bind has neither a public URL nor TLS.
2026-10-23 08:34:48 +08:00
yuez 01db49fb38 feat(daemon): add access modes and the local-browser login handshake
`PI2_ACCESS_MODE` (local|lan|tailscale) picks the bind address and the derived
CORS origins, `PI2_PUBLIC_URL` adds the external origin, and `PI2_ORIGINS` is now
additive instead of replacing the derived list. `daemon.json` and
`/api/v1/info` carry the mode and the public URL.

`POST /api/v1/console/session` is the `:PiWeb` handshake: loopback + the local
CLI token only, it mints or reuses the single "local browser" device and answers
`http://127.0.0.1:<port>/#t=<token>`. The token is stored plaintext next to
`devices.json` (0600) so repeated logins return the same credentials instead of
logging the already-open tab out; revoking the device drops it.
2026-10-23 08:34:39 +08:00
yuez 7e780515ac 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`.
2026-10-22 15:47:48 +08:00
yuez 5572ac0d84 fix(daemon): forward snapshot entries and map workspace errors
- Preserve the snapshot entries tail in the cache and WS frames (cold,
  cached and bus paths), so the browser receives {state, entries}.
- Await a plugin snapshot on the first subscribe of a fresh session.
- Return E_FORBIDDEN (403) for workspace paths outside PI2_WORKSPACE_ROOTS.
- Mint cli.token only after the singleton lock is held, so a second daemon
  cannot invalidate the running one.
- Add hostname/os/version/uptimeMs/pid/port to /api/v1/info and make
  /health reflect instance, workspace and auth state.
2026-10-21 20:42:02 +08:00
yuez 31f36302bd test(daemon): align the entries relay assertion with workspace.query{kind:entries} 2026-10-21 14:43:46 +08:00
yuez 18e3e0ab4e feat(cli): runnable daemon, local CLI, doctor, service files and smoke test
- composition root wiring config/auth/workspaces/instances/http
- singleton lock + daemon.json + port retry + local cli.token (admin scope)
- pi2 attach/status/doctor/pairing/install-service
- systemd user unit + launchd plist rendering (never auto-enabled)
- smoke.sh boots the real daemon on an ephemeral port and asserts auth/static/lifecycle
- 93 new tests (263 total), tsc + build + smoke green
2026-10-21 12:45:11 +08:00
yuez a495f2ac71 feat(instances): plugin socket server and one-nvim-per-workspace supervisor
- JSONL plugin server with hello token auth, frame cap, heartbeat and E_LEASE rejection
- PluginConnection with ack correlation, snapshot cache, per-epoch seq
- lazy spawn (headless nvim), degrade-on-crash with process_exit fanout, no auto-restart
- shutdown drain/stop with SIGTERM/SIGKILL escalation, RSS resources view
- 57 tests against a generated fake nvim
2026-10-21 11:50:51 +08:00
yuez 4e98ef8658 feat(workspaces): registry and header-only disk discovery
- atomic 0600 workspaces.json with corrupt-file recovery
- discovery reads only the first JSONL line for the authoritative cwd
- cache by dir mtime+count: cold 27-37ms / warm 9.6ms on 1313 files
- 38 tests, real-machine benchmark documented in the report
2026-10-21 11:14:12 +08:00
yuez ba3719fad9 feat(daemon): HTTP/WS/SSE surface with auth, static, command routing and event relay
- Hono app + ws upgrade server, ephemeral-port friendly, idempotent close
- device tokens (sha256 + timingSafeEqual), one-time pairing, Origin allowlist
- SPA static serving with traversal protection and cache policy
- command router with 5-min clientRequestId dedupe and protocol error mapping
- 66 tests against fake InstanceManager/WorkspaceStore/Bus
2026-10-21 11:14:12 +08:00
yuez 9d817f35b7 feat(protocol): wire contract, canonical reducer and golden fixtures
- v1 envelope across browser/daemon/plugin
- SessionState model + reducer rules (pi events + pi2:* derived events)
- fixtures for basic turn, queue/todo/attention and abort/exit
- 9 conformance tests pinning the reducer
2026-10-21 10:58:46 +08:00