diff --git a/PLAN.md b/PLAN.md index 18e674a..fd2bf06 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1020,6 +1020,12 @@ For hosts without hook support, the docs MUST state the protection tier plainly and its tier; `envseal init --host cursor` on a clean fixture produces a `.cursor/mcp.json` that a schema test validates. +**Shipped in v0.1.5:** `init` always merges Layer 1 `AGENTS.md`, then writes **every** matching +project host config (not first-wins). Launch is `npx -y @envseal/mcp-server` (`npx.cmd` on +Windows), never a bare `envseal-mcp` on PATH and never `$HOME` MCP. `--host` is a write +escape hatch, not a fake protection tier. Doctor fail-closes when the primary host’s MCP +is unwired. Detection does not inventory IDEs under `$HOME`. + ### T10.2 — Spec publication Copy Part I into `spec/sep-1/SPEC.md` with a conformance section: an implementation is SEP/1 conformant if it implements the seven tools, never returns values, and passes the published diff --git a/README.md b/README.md index cebc07b..f9e06ef 100644 --- a/README.md +++ b/README.md @@ -72,17 +72,22 @@ For a runnable walk-through of the whole lifecycle (`init` → `ensure --check` ## Connect your agent -Provisioning keys is only half of it: your agent asks for them through the broker, so the host has to be able to start the broker. For Claude Code, create `.mcp.json` at the project root: - -```json -{ - "mcpServers": { - "envseal-mcp": { "command": "envseal-mcp", "args": [] } - } -} +Provisioning keys is only half of it: your agent asks for them through the broker, so the host has to be able to start the broker. + +```bash +npm install -D @envseal/cli +npx envseal init ``` -Restart Claude Code afterwards. Copy-pasteable snippets for Cursor, Zed, Codex, Continue and the other hosts are in [docs/hosts/README.md](docs/hosts/README.md); installing the bundled plugin in `plugins/claude-code` on top of the MCP server is what earns tier A. +`init` always merges Layer 1 instructions into project-root `AGENTS.md` (any agent that reads instruction files can then run `envseal ensure` / `envseal run --` instead of asking for a paste). If this repo has project-local host markers (`.cursor/`, `.claude/`, …), or you ran the command from that IDE, it also writes the **project** MCP (or equivalent) config so the agent gets `env_declare` / `env_request` / `env_await` / `env_verify` / `env_use`. A repo used from Cursor and Claude Code gets both `.cursor/mcp.json` and `.mcp.json`. `init` does not scan `$HOME` or wire every IDE on the machine. + +Launch is `npx -y @envseal/mcp-server` (`npx.cmd` on Windows). Host MCP launchers do not search `node_modules/.bin`, so a bare `envseal-mcp` command will not start. Project MCP already has the workspace as cwd — `--project` is not baked into committed files. + +Do **not** put envseal in `~/.cursor/mcp.json` (or other user-global MCP files) as the default: those processes often start with `cwd` = `$HOME`, and `envseal-mcp` then exits `no project found`. If detection cannot see the IDE (bare terminal on an empty tree), `init` writes `AGENTS.md` only and prints: re-run from the IDE, or `envseal init --host cursor`. + +Reload MCP / restart the host, then `envseal doctor`. Doctor fails if an MCP-capable host’s project folder exists but `envseal-mcp` is not actually configured. + +Claude Code: `init` = protocol connected (Tier B via `.mcp.json`). Install `plugins/claude-code` for Tier A hooks. Snippets for every host: [docs/hosts/README.md](docs/hosts/README.md). ## Works with any agent diff --git a/VERIFICATION.md b/VERIFICATION.md index 4e7337c..639d836 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -249,6 +249,7 @@ what cannot be is listed as a runbook step, not claimed. | **E9** W4 adversarial battle-test (2026-08-25) | **PASS — 0 Critical open; 4 findings fixed and shipped in v0.1.2; 2 reclassified as correct behavior.** | ~55 scenarios across 9 phases against published v0.1.1 artifacts (`docs/verification/W4-battle-test.md`, probes in `.commandcode/probe-w4-p*.mjs`). Redaction engine unbeaten: raw/stderr/multi-secret/10MB-volume all redacted, audit never holds values, MCP server survived malformed frames + floods with zero failures, plugin deny matrix held incl. traversal paths, host-detection precedence held under fake-HOME. Fixed in v0.1.2 (23bedc0): **F2 High** ensure/set hang forever non-TTY → fail closed exit 4 in ~300ms; **F5 Med** detector missed sk-live-/bare-sk- OpenAI shapes → patterns added; **F1 Med** init laundered hostile pre-existing manifests → guard scan on read path; **F4 Low** missing-manifest run now warns on stderr. F6 (audit recreation) proven correct behavior; F3 (keychain sink) proven probe artifact — set honors declared sink end-to-end. Registry proof: v0.1.2 published with SLSA v1 provenance ([release run](https://github.com/NDilanka/envseal/actions/runs/32756572088)), clean-dir smoke green. Known documented boundaries: grandchild-process stdout not intercepted (broker-spawned direct stdio only); transformed encodings inside child output are out of literal-match scope by design. | | **E10** External-review fix + same-class audit sweep → v0.1.3 (2026-08-25) | **PASS — reviewer's finding fixed; 2-round audit complete; every finding fixed; released and registry-verified.** | External X review found `env_use` consent bound to displayed argv, not target content. Fixed (3a1d920): every argument naming a readable file SHA-256 fingerprinted before the dialog (fingerprints shown in it) and re-hashed immediately pre-spawn; mismatch → new `SEP_TARGET_CHANGED`, nothing executes, nothing cached. Proven by tests incl. mutation-between-approval-and-spawn refusal and settle-then-reprompt. Same-class audit (2 time-boxed subagents, findings verified against source before fixing) then closed in 711e7ff: hook denylist bypasses (wrapper/path-prefix readers, mid-command `< file` redirects, glob suffixes, printf/declare-p/here-string var leaks — with a fail-open regression caught by a 31-payload probe of the built bundle, now pinned in `.commandcode/probe-audit-fixes.mjs`); detector suppression buckets hardened (digest charset+length floors so `sha256:` labels can't hide sk-keys, SRI-shape required after `integrity=`, data-URI MIME/base64 validation, path bucket needs real path structure, URL bucket refuses credential-shaped query params); consent surfaces unified on shared `core/display.ts` with bidi/unicode-separator escaping (twins byte-identical again), loopback links show destination host, TEST_MODE stub announces every answered key, no-TTY error no longer advertises the ASSUME_YES bypass. Gates: full monorepo suite green, build/typecheck/lint clean on tracked code, plugin contract 165/165, detector 44/44. Release run [32815056545](https://github.com/NDilanka/envseal/actions/runs/32815056545) green incl. publish; all 9 packages live at 0.1.3 with SLSA v1 provenance; clean-machine smoke on the published artifact: install (108 pkgs) → `envseal version 0.1.3` → shipped `core/dist/display.js` present → status shows key present with fingerprint → `env_use` injects and child output returns `«redacted:PROBE_KEY»`, `redactedCount: 1`. | | **E11** Security hardening review → v0.1.4 (2026-08-25) | **PASS — released and registry-verified.** | Whole-repo review findings landed in [PR #1](https://github.com/NDilanka/envseal/pull/1) (`fa80cff`). Lockstep bump `0.1.3` → `0.1.4`. Release run [32848761172](https://github.com/NDilanka/envseal/actions/runs/32848761172) published all 9 `@envseal/*` packages; `@envseal/cli@0.1.4` is `latest` with SLSA v1 provenance. Residuals unchanged: Darwin keychain argv, hook fail-open default, MCP stdio host-trust. | +| **E12** Init host wiring (T10.1) → v0.1.5 (2026-08-25) | **PASS — implementation + docs; registry pending tag.** | `envseal init` always merges Layer 1 `AGENTS.md` and writes project-scoped MCP (`npx -y @envseal/mcp-server`, `npx.cmd` on Windows) for every matching project marker or `--host`. Does not crawl `$HOME`. Doctor fail-closes on unwired MCP / missing instructions (`agentWiring`). `--host` is a write override, not a fake protection tier. Lockstep bump `0.1.4` → `0.1.5`. Release run TBD until tag `v0.1.5` publishes. | Launch is authorised only when every row is filled with recorded evidence. diff --git a/docs/cli-contract.md b/docs/cli-contract.md index 99531c3..c823aa6 100644 --- a/docs/cli-contract.md +++ b/docs/cli-contract.md @@ -28,30 +28,54 @@ The one way to proceed headlessly is `envseal run`'s own confirmation bypass: `- ### `envseal init [--host ]` -Initialize `env.schema.jsonc` at the project root. +Initialize `env.schema.jsonc` at the project root, merge Layer 1 `AGENTS.md`, +and write project host config for every matching marker (or `--host`). **Flags:** -- `--host ` — Override host detection. Valid values: `claude-code`, `cursor`, `continue`, `aider`, `windsurf`, `cline`, `zed`, `codex`, `jetbrains`, `goose`, `copilot`, `generic`, `unknown`; anything else is rejected with exit 2. When an override is given, the reported tier is what that host id implies, not evidence about this project — `envseal doctor` reports what is actually detected. +- `--host ` — Write this host's project config (comma-separated ok). Valid values: `claude-code`, `cursor`, `continue`, `aider`, `windsurf`, `cline`, `zed`, `codex`, `jetbrains`, `goose`, `copilot`, `generic`, `unknown`, `openhands`; anything else is rejected with exit 2. `--host` selects files to write; `protectionTier` in the output is evidence-based (`detectHost` after write), not a fake tier from the flag. `envseal doctor` reports detected protection. - `--json` — Output as JSON. - `--project ` — Project root (default: auto-detect). +`init` always merges `plugins/generic/AGENTS.md` into project-root `AGENTS.md` +(create or append; never clobbers unrelated content). It then writes each +matching **project** config (`.cursor/mcp.json`, `.mcp.json`, …) using +`npx -y @envseal/mcp-server` (`npx.cmd` on Windows). It never writes +`~/.cursor/mcp.json` or other `$HOME` configs. With no project markers and no +IDE process env, it writes `AGENTS.md` only. + **JSON output:** ```json { "manifestPath": "/path/to/env.schema.jsonc", - "host": "claude-code", - "protectionTier": "C", + "host": "cursor", + "protectionTier": "B", + "requestedHosts": ["cursor"], + "wiredHosts": ["cursor"], + "wiringSource": "flag", "scanned": 14, "added": ["OPENAI_API_KEY"], "updated": [], "unchanged": [], "secretKeys": ["OPENAI_API_KEY"], "configKeys": [], - "entries": 1 + "entries": 1, + "agentsMd": { "action": "created", "path": "/path/to/AGENTS.md" }, + "hostWiring": [ + { "id": "cursor", "action": "created", "path": "/path/to/.cursor/mcp.json" } + ], + "cursorWiring": { + "mcp": "created", + "rules": "created", + "mcpPath": "/path/to/.cursor/mcp.json", + "rulesPath": "/path/to/.cursor/rules/envseal.mdc" + } } ``` -`host` is the detected host id (`"unknown"` when nothing matched); `protectionTier` is `"A"`, `"B"`, or `"C"`; `scanned` is the number of files scanned; `added`/`updated`/`unchanged` list the manifest entries by outcome; `secretKeys`/`configKeys` split the declared keys by their `secret` flag; `entries` is the total entry count. +`host` / `protectionTier` are from detection after write. `wiringSource` is +`"project"` | `"process"` | `"flag"` | `"none"`. `requestedHosts` is present +only when `wiringSource` is `"flag"`. `wiredHosts` / `hostWiring` list what +Layer 2 wrote. On Cursor, `cursorWiring` still reports `{ mcp, rules, mcpPath, rulesPath }` (`created` / `merged` / `unchanged` / `skipped`). **Exit codes:** Always 0 on success. @@ -262,7 +286,9 @@ envseal run -- npm test ### `envseal doctor` -Audit the project configuration. Reports: project root, manifest path, detected host + tier + recommendation, gitignore coverage, file permissions, count of missing required keys. +Audit the project configuration. Reports: project root, manifest path, detected host + tier + recommendation, **agent wiring** (MCP + Layer 1 `AGENTS.md`), gitignore coverage (ignore-rule semantics, not substring match), `.env` tracked/permissions, `hookFailClosed`, count of missing required keys. + +Folder presence is not wiring. For the detected **primary** host, doctor checks the project config `init` would have written. An empty `.cursor/mcp.json` `mcpServers` map is unwired (exit 1). Continue and Goose are **not OOTB** (print-only MCP). With no `env.schema.jsonc` in the project there is nothing to audit: `doctor` fails with `SEP_NOT_DECLARED` and exit 2 (same as `ensure`) instead of printing @@ -275,10 +301,13 @@ an empty bill of health. **Human output example:** ``` Project root: /Users/alice/myproject -Host: Claude Code (Tier A) - Found .claude/ directory - Tier A host with full protocol + interception hooks. Secrets are maximally protected. +Host: Cursor (Tier B) + Found .cursor/ directory + Tier B host with protocol + advisory guardrails only. ... +Agent wiring: MCP ok, instructions ok + Cursor MCP is wired (project .cursor/mcp.json). Gitignore covers .env: yes +Hook on internal error: fail-open (default) Missing required keys: 1 - OPENAI_API_KEY ``` @@ -289,11 +318,18 @@ Missing required keys: 1 "projectRoot": "/Users/alice/myproject", "manifestPath": "/Users/alice/myproject/env.schema.jsonc", "host": { - "id": "claude-code", - "name": "Claude Code", - "tier": "A", - "reason": "Found .claude/ directory", - "recommendation": "Tier A host with full protocol + interception hooks. Secrets are maximally protected." + "id": "cursor", + "name": "Cursor", + "tier": "B", + "reason": "Found .cursor/ directory", + "recommendation": "Tier B host with protocol + advisory guardrails only. ..." + }, + "agentWiring": { "mcp": "ok", "instructions": "ok" }, + "mcp": { + "wired": true, + "status": "wired", + "message": "Cursor MCP is wired (project .cursor/mcp.json).", + "commandOk": null }, "gitignore": { "exists": true, @@ -304,14 +340,20 @@ Missing required keys: 1 "isTracked": false, "permissionsOk": true }, + "hookFailClosed": false, "missingRequiredCount": 1, "missingRequired": ["OPENAI_API_KEY"] } ``` +`agentWiring.mcp` is `"ok"` | `"missing"` | `"spawn_failed"`. `instructions` is +`"ok"` | `"missing"`. For MCP-capable hosts the JSON also includes +`mcp: { wired, status, message, commandOk }`. `message` tells the caller to run +`envseal init` (or the exact JSON to merge); it never says to copy from `plugins/`. + **Exit codes:** -- 0 — All checks passed; no missing required keys. -- 1 — One or more required keys are missing. +- 0 — All checks passed; no missing required keys; primary-host MCP wired when required; Layer 1 instructions present. +- 1 — One or more required keys are missing, or the agent is unwired (MCP missing/spawn_failed, missing `AGENTS.md` imperative, or Aider `read:` lists `.env`). --- diff --git a/docs/hosts/README.md b/docs/hosts/README.md index c26bee0..c773bb6 100644 --- a/docs/hosts/README.md +++ b/docs/hosts/README.md @@ -1,50 +1,54 @@ # Host integration matrix Which binding tier each host uses, which protection tier it gets, and where the -config lives. Every per-host page has a copy-pasteable snippet; entries marked -`[VERIFY]` should be checked against your installed version's documentation -before relying on them. +config lives. The primary path is `npm i -D @envseal/cli` && `npx envseal init` +**in this project** (or this IDE session) — not every IDE on the PC. `init` +merges `AGENTS.md` (Layer 1) always, then writes each matching **project** +config (Layer 2). `--host ` is the escape hatch when detection cannot +see the IDE. Entries marked `[VERIFY]` should be checked against your installed +version's documentation before relying on them. -| Host | Binding tier | Protection tier | Config file | +| Host | Binding tier | Protection tier | What `init` writes | |---|---|---|---| -| claude-code | 1 (MCP) — plus bundled hooks | **A** | `.claude-plugin/plugin.json` or `.mcp.json` | -| cursor | 1 (MCP) | **B** | `.cursor/mcp.json` or `~/.cursor/mcp.json` | -| continue | 1 (MCP) | **B** | `~/.continue/config.yaml` | +| claude-code | 1 (MCP) — plus bundled hooks | **B** OOTB, **A** with plugin | `.mcp.json` + `.claude/` marker. Plugin = A | +| cursor | 1 (MCP) | **B** | `.cursor/mcp.json` + `.cursor/rules/envseal.mdc` | +| continue | 1 (MCP) | **B** | Project `.continue/config.yaml` (copy-paste). **Not OOTB** — Continue loads `~/.continue/config.yaml`; envseal does not write `$HOME` | | windsurf | 1 (MCP) | **B** | `.windsurf/mcp_config.json` `[VERIFY]` | | cline | 1 (MCP) | **B** | `.cline/mcp_settings.json` `[VERIFY]` | -| zed | 1 (MCP) | **B** | `.zed/settings.json` `[VERIFY]` | -| codex | 1 (MCP) | **B** | `~/.codex/config.toml` `[VERIFY]` | -| goose | 1 (MCP) | **C** | `~/.config/goose/config.yaml` `[VERIFY]` | -| copilot-agent | 1 (MCP) | **B** | `github.copilot.mcp` VS Code setting `[VERIFY]` | +| zed | 1 (MCP) | **B** | `.zed/settings.json` `mcp` key `[VERIFY]` | +| codex | 1 (MCP) | **B** | Project `.codex/config.toml` `[VERIFY]` | +| goose | 1 (MCP) | **C** | Prints `goose mcp add` + yaml. **Not OOTB**. Marker `.goose/` | +| copilot-agent | 1 (MCP) | **B** | `.vscode/settings.json` `github.copilot.mcp` `[VERIFY]` + `AGENTS.md` | | jetbrains | 1 (MCP) | **B** | `.idea/mcp.json` `[VERIFY]` | -| aider | 4 (CLI) | **C** | `.aider.conf.yml` + `/run` | -| openhands | 4 (CLI) | **B** | `AGENTS.md` + terminal tool `[VERIFY]` | +| aider | 4 (CLI) | **C** | `.aider.conf.yml` (`read:` without `.env`) + `AGENTS.md` | +| openhands | 4 (CLI) | **B** | `AGENTS.md` only `[VERIFY]` (sandbox / TTY) | | shell-agent | 4 (CLI) | **B** | `AGENTS.md` / shell recipe | -> **What `envseal doctor` actually detects:** claude-code, cursor, continue, -> aider, windsurf, cline, zed, codex, jetbrains, goose, and copilot are -> identified by name. Project-root markers: `.cursor/`, `.continue/`, -> `.windsurf/`, `.cline/`, `.zed/`, `.codex/`, `.idea/`, `goose.config.yaml` / -> `.goose/`, aider's `aider.conf.yml`-style files, and `copilot` settings -> inside `.vscode/settings.json` for copilot. cline, zed, codex and goose are -> also detected via global config directories under your home (or -> `CLINE_ROOT` / `ZED_EDITOR` / `CODEX_ROOT` / `GOOSE_ROOT`), windsurf via -> `~/.codeium/windsurf/`. claude-code reports Tier A only with visible hook -> wiring (envseal hooks in `.claude/settings.json`, or the plugin copied to -> `.claude/plugins/envseal/`); otherwise Tier B. continue is detected only via -> a `.continue/` directory at the *project* root — a global -> `~/.continue/config.yaml` alone reports `Unknown Host (Tier C)`, as does any -> host with none of the markers above; openhands and shell-agent have no -> host-specific detection, so they report `Unknown Host (Tier C)` — or -> `Generic Agent (Tier B)` when an `AGENTS.md` is present at the root. For the -> hosts identified by name, doctor prints the protection tier shown in the -> table; the column also describes what each host's documented setup achieves. +> **What `envseal doctor` actually detects (labeling):** claude-code, cursor, +> continue, aider, windsurf, cline, zed, codex, jetbrains, goose, and copilot +> are identified by **project-root** markers: `.claude/`, `.cursor/`, +> `.continue/`, `.windsurf/`, `.cline/`, `.zed/`, `.codex/`, `.idea/`, +> `goose.config.yaml` / `.goose/`, aider's `aider.conf.yml`-style files, and +> `copilot` settings inside `.vscode/settings.json`. Process env +> (`CLAUDECODE`, `CURSOR_*`, `CLINE_ROOT`, `ZED_EDITOR`, `CODEX_ROOT`, +> `GOOSE_ROOT`) is used only when the project has no marker of its own. +> +> `$HOME` installs are **not** this project's agent. `~/.codex/` alone does +> **not** report Codex (Unknown Host). `~/.codeium/windsurf/`, `~/.cline/`, +> `~/.config/zed/` / `~/.zed/` on a bare tree report **Generic Agent**, not a +> named host. `~/.continue/config.yaml` alone is Unknown Host. Doctor never +> writes those global files. +> +> Folder presence is not wiring. An empty `.cursor/mcp.json` is unwired +> (non-zero). JSON includes `agentWiring: { mcp, instructions }`. +> claude-code reports Tier A only with visible hook wiring; `.mcp.json` alone +> is Tier B + MCP wired/missing as a separate field. ## Tiers | Tier | Meaning | Hosts | |---|---|---| -| **A** | protocol + interception hooks (tool-call and user-message filtering) | claude-code | +| **A** | protocol + interception hooks (tool-call and user-message filtering) | claude-code (plugin) | | **B** | protocol + advisory guardrails (rules file, docs, pre-commit) | cursor, continue, windsurf, cline, zed, codex, copilot-agent, jetbrains, openhands, shell-agent | | **C** | protocol only | goose, aider | @@ -56,15 +60,27 @@ value just like a dotenv one. ## MCP server command -Every MCP snippet below registers the same server, invoked as `envseal-mcp` -(the binary shipped by `@envseal/mcp-server`, a dependency of `@envseal/cli`). -Set `command` to the absolute path of `packages/mcp-server/dist/bin.js` (this -repo) when `envseal-mcp` is not on your `PATH`, and pass `--project ` -if the host does not launch MCP servers with the project root as cwd. +Every MCP snippet `init` writes uses the same server: + +```json +{ + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] +} +``` + +On Windows the command is `npx.cmd`. Do not use a bare `envseal-mcp` binary: +host launchers do not search `node_modules/.bin`. Do not bake `--project` into +a committed project file. Do not recommend `~/.cursor/mcp.json` (or other +user-global MCP) as the default — those processes often start with `cwd` = +`$HOME`. + +If several project markers exist, `init` writes all of them. ## Generic instruction file -For any host that reads instruction files — and for plain shell agents — start -from `plugins/generic/AGENTS.md`. It tells the agent, imperatively: never read -`.env`, never echo environment variables, use `envseal ensure` / -`envseal run --` instead. \ No newline at end of file +Layer 1: `init` merges `plugins/generic/AGENTS.md` into project-root +`AGENTS.md`. It tells the agent, imperatively: never read `.env`, never echo +environment variables, use `envseal ensure` / `envseal run --` instead. That is +the working path for OpenHands, Aider-adjacent hosts, Copilot-without-MCP, and +unknown hosts. diff --git a/docs/hosts/aider.md b/docs/hosts/aider.md index 458cb5c..f45d96a 100644 --- a/docs/hosts/aider.md +++ b/docs/hosts/aider.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 4 — CLI contract (`envseal` subcommands) | | **Protection tier** | **C** — protocol only | -| **Config file** | `.aider.conf.yml` + `/run` recipe | +| **Config file** | `.aider.conf.yml` + `/run` recipe + `AGENTS.md` | Aider has no MCP client, so it integrates at **Tier 4** via the `envseal` binary. Nothing intercepts leaks, and Aider *renders every file it reads into @@ -13,8 +13,13 @@ integration is written around that. ## Install -Copy `plugins/aider/.aider.conf.yml` (or merge the two lines below into your -config): +```sh +npm install -D @envseal/cli +npx envseal init --host aider +``` + +`init` merges Layer 1 `AGENTS.md` and merges `plugins/aider/.aider.conf.yml` so +`.env` is **not** on the `read:` list: ```yaml # .aider.conf.yml — NEVER add `.env` or `.env.*` to `read` @@ -23,8 +28,7 @@ read: - .env.example ``` -The `read` list is the guardrail: only declaration and placeholder files are -ever brought into context. +Doctor fails if `.env` appears under `read:`. ## Tier-4 usage (Aider `/run`) @@ -43,7 +47,7 @@ secret values inside Aider. Tier C has no guardrails. Prefer the `keychain` sink to keep the value out of `.env` entirely: it is stored in the OS-backed store and nothing is written to -`.env`, not even a reference. Note the sink both stores and resolves today — +`.env` — not even a reference. Note the sink both stores and resolves today — `envseal run` injects a keychain-stored value just like a dotenv one: ```jsonc @@ -60,4 +64,4 @@ Tier C has no guardrails. Prefer the `keychain` sink to keep the value out of The `sink: "keychain"` entry above is valid and — as noted above — resolves too, as do the provider sinks (`vault`, `1password`, `doppler`, `sops`), each delegating to its provider CLI. On Aider prefer keychain for high-value keys -you want off disk, and dotenv when the command needs the value. \ No newline at end of file +you want off disk, and dotenv when the command needs the value. diff --git a/docs/hosts/claude-code.md b/docs/hosts/claude-code.md index 5dc3d10..a9f075b 100644 --- a/docs/hosts/claude-code.md +++ b/docs/hosts/claude-code.md @@ -3,51 +3,51 @@ | | | |---|---| | **Binding tier** | 1 — MCP over stdio | -| **Protection tier** | **A** — protocol + interception hooks | -| **Config file** | `.claude-plugin/plugin.json` (the plugin in this repo, `plugins/claude-code`) or `.mcp.json` | +| **Protection tier** | **B** from `init`; **A** with the plugin | +| **Config file** | `.mcp.json` (protocol) plus `plugins/claude-code` (hooks) | Claude Code is the only host with **Tier A**: the plugin in this repo (`plugins/claude-code`) adds a `PreToolUse` guard that denies reads of `.env`/secret paths and env-dumping shell commands, a `UserPromptSubmit` redactor that intercepts pasted keys, a `SessionStart` note and statusline. -Prefer the plugin. +Prefer the plugin. `init` does **not** claim Tier A — that is evidence-based. -## Install (Tier A plugin) +## Install (protocol, Tier B) ```sh -envseal init --host claude-code +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host claude-code ``` -Note that `init` prints `(protection tier C)` for any `--host` override — it -cannot verify wiring from a flag alone — so trust `envseal doctor`'s -evidence-based report instead. - -or install the plugin from this repo (`plugins/claude-code`, `.claude-plugin/plugin.json`). -`envseal doctor` reports `Host: Claude Code (Tier A)` only when it can see the -hooks actually installed: an envseal + hooks entry in the project or home -`.claude/settings.json` (or `settings.local.json`), or the plugin copied under -`.claude/plugins/envseal/`. With only `.claude-plugin/plugin.json` present, -doctor reports `Claude Code (Tier B)`. Inside a Claude Code session -(`CLAUDECODE` set), Claude Code is detected either way, but Tier A still -requires the visible hook wiring. - -## Config snippet (bare MCP, no hooks) - -If you only want the protocol without the plugin, project-scoped `.mcp.json`: +`init` writes project `.mcp.json` with `npx -y @envseal/mcp-server` and merges +`AGENTS.md`. That is protocol connected (Tier B). Restart Claude Code. ```json { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } ``` -Claude Code reads MCP config from `.mcp.json` at the project root (documented by -Anthropic); without the plugin you are Tier B, not A. +## Install (Tier A plugin) + +Install the plugin from this repo (`plugins/claude-code`, +`.claude-plugin/plugin.json`). `envseal doctor` reports `Host: Claude Code +(Tier A)` only when it can see the hooks actually installed: an envseal + hooks +entry in the project or home `.claude/settings.json` (or `settings.local.json`), +or the plugin copied under `.claude/plugins/envseal/`. With only `.mcp.json` +present, doctor reports `Claude Code (Tier B)` and `agentWiring.mcp` separately +(`ok` vs `missing`). Inside a Claude Code session (`CLAUDECODE` set), Claude +Code is detected either way, but Tier A still requires the visible hook wiring. + +`--host` is an override of which files to write, not a claim about protection. +Trust `envseal doctor`. ## Notes @@ -56,4 +56,4 @@ Anthropic); without the plugin you are Tier B, not A. - Tier A still does not defend against `env_use` exfiltration or a user who clicks through a confirmation dialog (see `docs/residual-risks.md`). - The `keychain` sink remains available and recommended for long-lived, high-value - keys even on Tier A. \ No newline at end of file + keys even on Tier A. diff --git a/docs/hosts/cline.md b/docs/hosts/cline.md index 0900800..f965c60 100644 --- a/docs/hosts/cline.md +++ b/docs/hosts/cline.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory instructions | -| **Config file** | `.cline/mcp_settings.json` (project) or `~/.cline/mcp_settings.json` (global) | +| **Config file** | `.cline/mcp_settings.json` (project) | Cline is **Tier B**: it speaks MCP but has no interception hooks. @@ -15,14 +15,22 @@ for you.]` ## Install -`.cline/mcp_settings.json`: +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host cline +``` + +`init` writes project `.cline/mcp_settings.json`. It does not write `~/.cline/`. +A global `~/.cline/` install on a bare tree is labeled Generic Agent, not Cline. ```json { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } @@ -30,8 +38,8 @@ for you.]` Restart/reload Cline, confirm `envseal-mcp` connects, then run `envseal doctor`. The detector recognizes a `.cline/` directory at the project -root, the global `~/.cline/` config directory, or `CLINE_ROOT`, and reports -`Host: Cline (Tier B)`. +root, or `CLINE_ROOT` when there are no project markers. Doctor fails if the +project file has no `envseal-mcp`. ## Keychain recommendation (Tier B) diff --git a/docs/hosts/codex.md b/docs/hosts/codex.md index a0cb2e6..d095094 100644 --- a/docs/hosts/codex.md +++ b/docs/hosts/codex.md @@ -4,28 +4,39 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory instructions | -| **Config file** | `~/.codex/config.toml` | +| **Config file** | Project `.codex/config.toml` (preferred). Global `~/.codex/config.toml` is not written | Codex CLI is **Tier B**: it gained MCP tool support, but has no interception hooks that can stop a leaked shell command from reaching the transcript. -Note on detection: `envseal doctor` recognizes a `.codex/` directory at the -project root, the global `~/.codex/` config directory, or `CODEX_ROOT`, and -reports `Host: Codex CLI (Tier B)`. +Doctor recognizes a `.codex/` directory at the project root, or `CODEX_ROOT` +when there are no project markers. **`~/.codex/` alone is not Codex** — a +global install is not this project's agent, and doctor reports Unknown Host. +envseal does not write `$HOME`. `[VERIFY: MCP support in Codex CLI is recent and the config schema is still moving — some builds read `[mcp_servers.]` from `~/.codex/config.toml`, others use a `mcp.json` side file, and the field names (command/args) have changed once already. Confirm the exact shape against your installed -`codex --help` / version docs.]` +`codex --help` / version docs. Project `.codex/` is preferred so cwd is the +workspace; if your build only reads the global file, merge the block by hand +and pass `--project` only in that global opt-in, which envseal does not write.]` ## Install -`~/.codex/config.toml`: +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host codex +``` + +`init` writes project `.codex/config.toml`: ```toml [mcp_servers.envseal-mcp] -command = "envseal-mcp" +command = "npx" +args = ["-y", "@envseal/mcp-server"] ``` Run `codex` in the project directory, confirm the `envseal-*` tools appear in diff --git a/docs/hosts/continue.md b/docs/hosts/continue.md index c7ad337..33bc7a1 100644 --- a/docs/hosts/continue.md +++ b/docs/hosts/continue.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory config only | -| **Config file** | `~/.continue/config.yaml` (or `config.json`) | +| **Config file** | `~/.continue/config.yaml` (global) — **not OOTB** | Continue is **Tier B**: it speaks MCP but has no interception hooks. `[VERIFY: recent Continue builds moved to a new HUB config schema; if a @@ -13,20 +13,30 @@ top-level `mcpServers` list is not accepted, use the legacy ## Install -Merge into `~/.continue/config.yaml`: +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host continue +``` + +`init` always writes Layer 1 `AGENTS.md`. For Continue it also creates project +`.continue/config.yaml` (a copy-paste snippet) so doctor can **detect** the +host. Continue currently loads MCP from `~/.continue/config.yaml`. envseal does +**not** write that global file (cwd hazard). Merge this block yourself: ```yaml mcpServers: - name: envseal-mcp - command: envseal-mcp - args: [] + command: npx + args: ["-y", "@envseal/mcp-server"] ``` -Restart Continue so the server connects. `envseal doctor` reports -`Host: Continue (Tier B)` only when a `.continue/` directory exists at the -project root — detection does not read your global config. If your project has -none, create an empty `.continue/` directory to be detected; otherwise doctor -reports Unknown Host (Tier C). +On Windows use `npx.cmd`. Doctor reports `Host: Continue (Tier B)` only when a +`.continue/` directory exists at the project root — detection does not read +your global config. MCP is **not OOTB**: `agentWiring.mcp` stays `missing` +until you merge the global file (envseal will not do it). Layer 1 `AGENTS.md` +is the working path. ## Keychain recommendation (Tier B) @@ -50,4 +60,4 @@ like a dotenv one: The `sink: "keychain"` entry above is valid and — as noted above — resolves too, as do the provider sinks (`vault`, `1password`, `doppler`, `sops`), each delegating to its provider CLI. Weigh dotenv's plaintext on disk against -Tier B's leak risk. \ No newline at end of file +Tier B's leak risk. diff --git a/docs/hosts/copilot-agent.md b/docs/hosts/copilot-agent.md index f54bb7b..8b9b243 100644 --- a/docs/hosts/copilot-agent.md +++ b/docs/hosts/copilot-agent.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory instructions | -| **Config file** | `github.copilot.mcp` VS Code setting, plus `AGENTS.md` | +| **Config file** | Project `.vscode/settings.json` `github.copilot.mcp`, plus `AGENTS.md` | Copilot (VS Code Copilot Chat / Copilot CLI agent) is **Tier B**: it reads `AGENTS.md` instruction files — which is the advisory guardrail — and recent @@ -18,28 +18,33 @@ VS Code/Copilot version's documentation.]` ## Install -VS Code `settings.json`: +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host copilot +``` + +`init` always merges Layer 1 `AGENTS.md` (Copilot reads it by default) and +merges `github.copilot.mcp` into **project** `.vscode/settings.json`: ```json { "github.copilot.mcp": [ { "name": "envseal-mcp", - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } ] } ``` -And, for every Copilot surface, add the instruction file -(`plugins/generic/AGENTS.md`) to your project root — Copilot reads `AGENTS.md` -by default. This is the advisory layer that makes Copilot defensibly `B`. `envseal doctor` reports `Host: GitHub Copilot (Tier B)` when `.vscode/settings.json` mentions Copilot (the `github.copilot.*` settings above qualify). Copilot has no unique project directory of its own, so without that settings marker doctor falls through to `Host: Generic Agent (Tier B)` -via the `AGENTS.md` file above. +via `AGENTS.md`. ## Keychain recommendation (Tier B) @@ -63,4 +68,4 @@ like a dotenv one: The `sink: "keychain"` entry above is valid and — as noted above — resolves too, as do the provider sinks (`vault`, `1password`, `doppler`, `sops`), each delegating to its provider CLI. On Tier B prefer keychain for high-value keys -you want off disk, and dotenv when the command needs plaintext. \ No newline at end of file +you want off disk, and dotenv when the command needs plaintext. diff --git a/docs/hosts/cursor.md b/docs/hosts/cursor.md index abef9d2..80b07a0 100644 --- a/docs/hosts/cursor.md +++ b/docs/hosts/cursor.md @@ -4,36 +4,45 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory rules file | -| **Config file** | `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global) | +| **Config file** | `.cursor/mcp.json` (project only) | Cursor is **Tier B**: it speaks MCP but has no interception hooks. The rules -file (`plugins/cursor/rules/envseal.mdc`) is advisory — it reduces accidents, +file (written to `.cursor/rules/envseal.mdc`) is advisory — it reduces accidents, it cannot block them. ## Install ```sh -mkdir -p .cursor/rules -cp plugins/cursor/mcp.json .cursor/mcp.json -cp plugins/cursor/rules/envseal.mdc .cursor/rules/ +npm install -D @envseal/cli +npx envseal init +# or, if this project has no `.cursor/` marker yet: +npx envseal init --host cursor ``` -Project-scoped `.cursor/mcp.json`: +`init` merges Layer 1 `AGENTS.md`, merges `envseal-mcp` into **project** +`.cursor/mcp.json` (other MCP servers are left intact), and copies the advisory +rules file if it is absent. It never writes `~/.cursor/mcp.json`: Cursor starts +a user-global MCP server with `cwd` set to the home directory, and `envseal-mcp` +then exits with `no project found`. + +Reload MCP in **Settings → MCP**. `envseal doctor` reports `Host: Cursor +(Tier B)` and fails if `.cursor/mcp.json` has no `envseal-mcp`. + +Project-scoped `.cursor/mcp.json` (POSIX). On Windows, `envseal init` writes +`"command": "npx.cmd"` instead of `"npx"` — Cursor does not search +`node_modules/.bin`, so a bare `envseal-mcp` command will not start. ```json { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } ``` -Restart Cursor, then `Settings → MCP` should show `envseal-mcp` connected. -`envseal doctor` should report `Host: Cursor (Tier B)`. - ## Keychain recommendation (Tier B) A Tier B host cannot stop a shell command from leaking a value. Set the @@ -57,4 +66,4 @@ The `sink: "keychain"` entry above is valid and — as noted above — resolves too, as do the provider sinks (`vault`, `1password`, `doppler`, `sops`), each delegating to its provider CLI. What still holds: `dotenv` is the only sink tools that read `.env` directly (Docker Compose, Next.js, Vite) will ever see. -On Cursor the leak risk usually outweighs that convenience. \ No newline at end of file +On Cursor the leak risk usually outweighs that convenience. diff --git a/docs/hosts/goose.md b/docs/hosts/goose.md index 2588764..4a3a7b3 100644 --- a/docs/hosts/goose.md +++ b/docs/hosts/goose.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **C** — protocol only | -| **Config file** | `~/.config/goose/config.yaml` | +| **Config file** | **Not OOTB** — print `goose mcp add` + yaml. Do not guess CLI flags | Goose is a **Tier C** host: it speaks MCP, but this integration provides no interception hooks and no interrogated advisory layer, so the guarantee is the @@ -12,29 +12,43 @@ protocol itself and nothing more. `[VERIFY: Goose's config and extension-registration format have changed between releases, and the project recommends registering MCP servers with its -own CLI rather than hand-editing config. Prefer the in-app command — e.g. -`goose mcp add` (check your build's help) — over the yaml below, which matches -one published shape of `~/.config/goose/config.yaml` and may not match yours.]` +own CLI rather than hand-editing config. Prefer the in-app command over the +yaml below, which matches one published shape of `~/.config/goose/config.yaml` +and may not match yours.]` ## Install ```sh -goose mcp add envseal-mcp -- envseal-mcp # [VERIFY: exact flags for your build] +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host goose ``` -or, if hand-editing `~/.config/goose/config.yaml`: +`init` writes Layer 1 `AGENTS.md` and creates a project `.goose/` marker so +doctor can label the host. It does **not** write `~/.config/goose/`. MCP is +not OOTB: doctor reports `agentWiring.mcp: missing` until you register the +server yourself. + +Printed (flags unverified — check `goose --help`): + +```sh +goose mcp add envseal-mcp -- npx -y @envseal/mcp-server # [VERIFY: exact flags for your build] +``` + +or, if hand-editing (unverified yaml): ```yaml mcp: servers: envseal-mcp: - cmd: envseal-mcp + cmd: npx + args: ["-y", "@envseal/mcp-server"] ``` -Confirm the tools appear in the session, then run `envseal doctor` — it -recognizes `goose.config.yaml`, a `.goose/` directory, the global -`~/.config/goose/` directory, or `GOOSE_ROOT`, and reports -`Host: Goose (Tier C)`. +Doctor recognizes `goose.config.yaml`, a `.goose/` directory, or `GOOSE_ROOT` +(when there are no project markers). A global `~/.config/goose/` on a bare +tree can label Goose for doctor only — `init` still will not write that file. ## Keychain recommendation (Tier C) @@ -57,4 +71,4 @@ touches disk: the value goes to the OS-backed store and nothing is written to The `sink: "keychain"` entry above is valid and — as noted above — resolves too, as do the provider sinks (`vault`, `1password`, `doppler`, `sops`), each delegating to its provider CLI. On Tier C prefer keychain for high-value keys -you want off disk, and dotenv when the command needs the value. \ No newline at end of file +you want off disk, and dotenv when the command needs the value. diff --git a/docs/hosts/jetbrains.md b/docs/hosts/jetbrains.md index f5bf512..3f194dc 100644 --- a/docs/hosts/jetbrains.md +++ b/docs/hosts/jetbrains.md @@ -4,14 +4,15 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory settings | -| **Config file** | `.idea/mcp.json` (project) or IDE MCP settings | +| **Config file** | `.idea/mcp.json` (project) | JetBrains IDEs (IntelliJ, PyCharm, etc.) are **Tier B**: their built-in MCP client exposes the seven tools, but nothing intercepts a shell command that leaks a value. -One note on detection: `envseal doctor` recognizes the `.idea/` project -directory and reports `Host: JetBrains IDE (Tier B)`. +Doctor recognizes the `.idea/` project directory and reports `Host: JetBrains +IDE (Tier B)`. Folder presence is not wiring: doctor fails if `.idea/mcp.json` +has no `envseal-mcp`. `[VERIFY: JetBrains MCP config location/format varies by product and version — project `.idea/mcp.json`, the shared `mcpServers` layout in IDE settings, and a @@ -21,13 +22,21 @@ file on your behalf. The snippet below is a common accepted shape.]` ## Install -`.idea/mcp.json`: +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host jetbrains +``` + +`init` merges project `.idea/mcp.json`: ```json { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp" + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } diff --git a/docs/hosts/openhands.md b/docs/hosts/openhands.md index ee51415..9a5dc7d 100644 --- a/docs/hosts/openhands.md +++ b/docs/hosts/openhands.md @@ -20,11 +20,20 @@ recipe below.]` ## Install +```sh +npm install -D @envseal/cli +npx envseal init +``` + +`init` merges `plugins/generic/AGENTS.md` into the project root (Layer 1). +OpenHands stays deployment-dependent: the `envseal` binary must be reachable +inside the sandbox, and `ensure` needs a TTY. There is no project MCP file +`init` can write. + 1. Make `envseal` available where the agent's commands run - (`npm i -g @envseal/cli`). -2. Add `plugins/generic/AGENTS.md` to the project root so OpenHands reads the - imperative rules (never read `.env`, never echo variables, use - `envseal ensure` / `envseal run --`). + (`npm i -D @envseal/cli` in the project the sandbox sees). +2. `AGENTS.md` tells OpenHands the imperative rules (never read `.env`, never + echo variables, use `envseal ensure` / `envseal run --`). 3. Give the agent a stable interactive path for `envseal ensure` when keys are missing (a terminal tool or configured user interaction); otherwise `ensure` fails with `no interactive surface` (exit 4), which is the correct, diff --git a/docs/hosts/shell-agent.md b/docs/hosts/shell-agent.md index db3a7fb..fd33789 100644 --- a/docs/hosts/shell-agent.md +++ b/docs/hosts/shell-agent.md @@ -38,9 +38,9 @@ since `status` exits nonzero only when a declared required key is missing. ## Instruction file -Add `plugins/generic/AGENTS.md` to the project root and point the agent at it. -For most agents this is the only advisory guardrail available — it is -**advisory**, not enforced: +Add `AGENTS.md` via `npx envseal init` (or `init --host generic`) and point the +agent at it. For most agents this is the only advisory guardrail available — it +is **advisory**, not enforced: - never read or copy `.env` / `.env.*` (except `.env.example`); - never `printenv`, bare `env`, `export -p`, or `echo $VAR`; diff --git a/docs/hosts/windsurf.md b/docs/hosts/windsurf.md index 42317d7..73808e4 100644 --- a/docs/hosts/windsurf.md +++ b/docs/hosts/windsurf.md @@ -4,7 +4,7 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory rules | -| **Config file** | `.windsurf/mcp_config.json` (project) or `~/.codeium/windsurf/mcp_config.json` (global) | +| **Config file** | `.windsurf/mcp_config.json` (project) | Windsurf is **Tier B**: it speaks MCP but has no interception hooks. @@ -18,17 +18,23 @@ your behalf.]` ## Install ```sh -mkdir -p .windsurf +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host windsurf ``` -`.windsurf/mcp_config.json`: +`init` writes project `.windsurf/mcp_config.json` (npx, not a bare +`envseal-mcp`). It does not write `~/.codeium/windsurf/`. A global Windsurf +install alone is **not** this project's agent: doctor labels a `$HOME`-only +tree as Generic Agent, not Windsurf. ```json { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } @@ -36,8 +42,8 @@ mkdir -p .windsurf Restart Windsurf, then confirm the server appears under MCP and run `envseal doctor`. The detector recognizes a `.windsurf/` directory at the -project root or the global `~/.codeium/windsurf/` config directory and reports -`Host: Windsurf (Tier B)`. +project root (or `init --host windsurf`). Doctor fails if that file has no +`envseal-mcp`. ## Keychain recommendation (Tier B) diff --git a/docs/hosts/zed.md b/docs/hosts/zed.md index 6f6a4fa..3b5ff56 100644 --- a/docs/hosts/zed.md +++ b/docs/hosts/zed.md @@ -4,13 +4,13 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory instructions | -| **Config file** | `.zed/settings.json` (project) or `~/.config/zed/settings.json` (global) | +| **Config file** | `.zed/settings.json` (project) | Zed is **Tier B**: it speaks MCP but has no interception hooks. -One note on detection: `envseal doctor` recognizes a `.zed/` directory at the -project root, the global Zed config directories (`~/.config/zed/`, `~/.zed/`), -or `ZED_EDITOR`, and reports `Host: Zed (Tier B)`. +Doctor recognizes a `.zed/` directory at the project root, or `ZED_EDITOR` when +there are no project markers. A global `~/.config/zed/` / `~/.zed/` install on +a bare tree is labeled Generic Agent, not Zed. envseal does not write `$HOME`. `[VERIFY: Zed's MCP config has changed between versions — older builds used a `mcp` block in `settings.json`, newer ones moved toward a dedicated @@ -20,19 +20,28 @@ file for you.]` ## Install -`.zed/settings.json` (or `~/.config/zed/settings.json`): +```sh +npm install -D @envseal/cli +npx envseal init +# or: +npx envseal init --host zed +``` + +`init` merges into project `.zed/settings.json` (sibling keys are left intact): ```json { "mcp": { "envseal-mcp": { - "command": "envseal-mcp" + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } } ``` -Restart Zed, confirm the server under `MCP`, then run `envseal doctor`. +Restart Zed, confirm the server under `MCP`, then run `envseal doctor`. Doctor +warns / fails if the file has no envseal server after write (`[VERIFY]`). ## Keychain recommendation (Tier B) diff --git a/docs/verification/W6-host-matrix.md b/docs/verification/W6-host-matrix.md index e7d1be9..53029b6 100644 --- a/docs/verification/W6-host-matrix.md +++ b/docs/verification/W6-host-matrix.md @@ -1,5 +1,13 @@ # W6 — Host integration matrix reality check +> **Historical.** This audit describes the tree *before* v0.1.5 host wiring. +> As of v0.1.5, `envseal init` writes project MCP/`AGENTS.md` for every matching +> marker (or `--host`); `detectHost()` knows the project-local markers listed in +> `docs/hosts/README.md`; `init --host` no longer hardcodes protection tier C; +> plugin snippets launch via `npx -y @envseal/mcp-server`. Do not treat the +> INCONSISTENT rows below as current defects. Leave the original findings intact +> as a record of what the earlier docs claimed. + Scope: documentation-consistency audit only; no live host integration, no file modified except this report. Sources of truth: `packages/cli/src/host.ts` (tier assignments), `packages/mcp-server/package.json` (`bin` = `envseal-mcp`), `packages/cli/package.json` (`bin` = `envseal`), `docs/cli-contract.md` (CLI diff --git a/packages/cli/package.json b/packages/cli/package.json index cae1c26..ca1aff4 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/cli", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 1c32d70..9fb00a6 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -15,7 +15,7 @@ import { revoke } from './commands/revoke.js'; import { mcp } from './commands/mcp.js'; import { init } from './commands/init.js'; -const VERSION = '0.1.4'; +const VERSION = '0.1.5'; async function main(): Promise { const argv = process.argv.slice(2); @@ -156,7 +156,7 @@ function showHelp(): void { Usage: envseal [options] Commands: - init [--host ] Initialize env.schema.jsonc + init [--host ] Initialize manifest, AGENTS.md, and host MCP ensure [--check] Prompt for all missing required keys (--check: report only, exit 0/1, never prompt) set Prompt for a single key diff --git a/packages/cli/src/cli-utils.ts b/packages/cli/src/cli-utils.ts index eaa3aef..89796b7 100644 --- a/packages/cli/src/cli-utils.ts +++ b/packages/cli/src/cli-utils.ts @@ -185,9 +185,9 @@ export function parseArgs(argv: string[]): ParsedArgs { const COMMAND_USAGE: Record = { init: `Usage: envseal init [--host ] [--json] [--project ] -Initialize env.schema.jsonc, declaring every environment-variable reference found by scanning the project. +Initialize env.schema.jsonc, merge AGENTS.md (Layer 1), and write project host MCP/config for every matching marker. - --host Override host detection. Valid values: claude-code, cursor, continue, aider, windsurf, cline, zed, codex, jetbrains, goose, copilot, generic, unknown. + --host Write this host's project config (comma-separated ok). Valid values: claude-code, cursor, continue, aider, windsurf, cline, zed, codex, jetbrains, goose, copilot, generic, unknown, openhands. --json Output as JSON. --project Project root (default: auto-detect).`, ensure: `Usage: envseal ensure [--check] [--json] [--project ] @@ -226,8 +226,8 @@ Asks for confirmation first; --yes (or ENVSEAL_ASSUME_YES=1) pre-approves it. --project Project root (default: auto-detect).`, doctor: `Usage: envseal doctor [--json] [--project ] -Audit the project configuration: detected host and tier, gitignore coverage, -file permissions, missing required keys. +Audit the project configuration: detected host and tier, agent wiring (MCP + +AGENTS.md), gitignore coverage, file permissions, missing required keys. --json Output as JSON. --project Project root (default: auto-detect).`, diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index 4eed276..6be0452 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -7,6 +7,7 @@ import { EXIT } from '../exit-codes.js'; import { detectHost } from '../host.js'; import { createBroker } from '../cli-utils.js'; import { finish } from '../exit.js'; +import { inspectPrimaryHostWiring, wiringFailsDoctor } from '../host-wiring/inspect.js'; export async function doctor(root: string, json: boolean): Promise { try { @@ -44,6 +45,7 @@ export async function doctor(root: string, json: boolean): Promise { } const host = detectHost(root); + const inspection = inspectPrimaryHostWiring(root, host.id, { probe: true }); const output = { projectRoot: root, manifestPath, @@ -54,6 +56,7 @@ export async function doctor(root: string, json: boolean): Promise { reason: host.reason, recommendation: host.recommendation, }, + agentWiring: inspection.wiring, gitignore: { exists: existsSync(gitignorePath), covers: gitignoreCovers, @@ -66,6 +69,16 @@ export async function doctor(root: string, json: boolean): Promise { hookFailClosed, missingRequiredCount: status.missingRequired.length, missingRequired: status.missingRequired, + ...(inspection.mcp === undefined + ? {} + : { + mcp: { + wired: inspection.mcp.wired, + status: inspection.mcp.status, + message: inspection.mcp.message, + commandOk: inspection.mcp.commandOk, + }, + }), }; if (!json) { @@ -73,6 +86,13 @@ export async function doctor(root: string, json: boolean): Promise { console.log(`Host: ${host.name} (Tier ${host.tier})`); console.log(` ${host.reason}`); console.log(` ${host.recommendation}`); + console.log( + `Agent wiring: MCP ${inspection.wiring.mcp}, instructions ${inspection.wiring.instructions}`, + ); + if (inspection.notOotb) { + console.log(' This host is not OOTB (print-only MCP). Layer 1 AGENTS.md is the working path.'); + } + console.log(` ${inspection.message}`); console.log(`Gitignore covers .env: ${gitignoreCovers ? 'yes' : 'no'}`); console.log( `Hook on internal error: ${hookFailClosed ? 'fail-closed' : 'fail-open (default)'}`, @@ -87,8 +107,7 @@ export async function doctor(root: string, json: boolean): Promise { emit(json, '', output); } - // Exit with UNSATISFIED if required keys are missing - if (status.missingRequired.length > 0) { + if (status.missingRequired.length > 0 || wiringFailsDoctor(inspection)) { finish(EXIT.UNSATISFIED); return; } diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index a821a3c..66cf364 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1,29 +1,11 @@ import { projectPaths, loadManifest, declareEntries, scanManifestEntry } from '@envseal/core'; import { SepError } from '@envseal/protocol'; import { emit, fail } from '../output.js'; -import { detectHost } from '../host.js'; +import { detectHost, resolveInitHostIds } from '../host.js'; import { scanForEnvKeys, entryForKey } from '../scan.js'; import { EXIT } from '../exit-codes.js'; import { finish } from '../exit.js'; - -// The ids detectHost can ever return. --host used to accept any string -// silently, recording a host detection would never report and printing a tier -// computed for a fiction. -const KNOWN_HOST_IDS = [ - 'claude-code', - 'cursor', - 'continue', - 'aider', - 'windsurf', - 'cline', - 'zed', - 'codex', - 'jetbrains', - 'goose', - 'copilot', - 'generic', - 'unknown', -]; +import { applyHostWiring } from '../host-wiring/apply.js'; export async function init( root: string, @@ -31,10 +13,9 @@ export async function init( hostOverride?: string, ): Promise { try { - if (hostOverride !== undefined && !KNOWN_HOST_IDS.includes(hostOverride)) { - console.error( - `Error: unknown --host '${hostOverride}'. Valid values: ${KNOWN_HOST_IDS.join(', ')}.`, - ); + const resolved = resolveInitHostIds(root, hostOverride); + if (resolved.error !== undefined) { + console.error(`Error: ${resolved.error}`); finish(EXIT.USAGE); return; } @@ -73,14 +54,20 @@ export async function init( const result = declareEntries(paths, entries); const manifest = loadManifest(paths); - const host = hostOverride - ? { id: hostOverride, name: hostOverride, tier: 'C' as const, reason: 'specified with --host', recommendation: '' } - : detectHost(root); + const wiring = applyHostWiring(root, resolved.ids); + // Evidence after write: --host cursor on a bare tree now has `.cursor/`. + // Never invent a fake tier from the flag alone. + const detected = detectHost(root); + const cursorEntry = wiring.hosts.find((h) => h.id === 'cursor'); + const cursorWiring = wiring.cursor; const output = { manifestPath: paths.manifest, - host: host.id, - protectionTier: host.tier, + host: detected.id, + protectionTier: detected.tier, + requestedHosts: resolved.source === 'flag' ? resolved.ids : undefined, + wiredHosts: resolved.ids, + wiringSource: resolved.source, scanned: discovered.length, added: result.added, updated: result.updated, @@ -88,6 +75,25 @@ export async function init( secretKeys: discovered.filter((d) => d.secret).map((d) => d.key), configKeys: discovered.filter((d) => !d.secret).map((d) => d.key), entries: manifest?.entries.length ?? 0, + agentsMd: { + action: wiring.agentsMd.action, + path: wiring.agentsMd.path, + }, + hostWiring: wiring.hosts.map((h) => ({ + id: h.id, + action: h.action, + path: h.path, + })), + ...(cursorWiring === undefined + ? {} + : { + cursorWiring: { + mcp: cursorWiring.mcp, + rules: cursorWiring.rules, + mcpPath: cursorWiring.mcpPath, + rulesPath: cursorWiring.rulesPath, + }, + }), }; if (json) { @@ -111,26 +117,43 @@ export async function init( console.log(` Config (not prompted): ${config.map((s) => s.key).join(', ')}`); } } - console.log(` Host: ${host.name} (protection tier ${host.tier})`); - if (host.recommendation) console.log(` ${host.recommendation}`); - if (hostOverride) { - // The override line above is what was ASKED for, not what is here. An - // auto-detected init on the same project can print a different tier, and - // doctor is the one that reports evidence. - console.log(' Override recorded; envseal doctor reports what is actually detected.'); - } - if (host.id === 'claude-code') { - // Without this the first run ends at a manifest and no connection: init - // writes env.schema.jsonc but nothing tells the user the agent still has - // to be pointed at the broker. - console.log(''); - console.log('Connect your agent: create .mcp.json in the project root containing'); - console.log(' {"mcpServers":{"envseal-mcp":{"command":"envseal-mcp","args":[]}}}'); + + console.log(` AGENTS.md: ${wiring.agentsMd.action} (Layer 1 — envseal ensure / envseal run --)`); + console.log(` Detected host: ${detected.name} (protection tier ${detected.tier})`); + console.log(` ${detected.reason}`); + if (detected.recommendation) console.log(` ${detected.recommendation}`); + if (resolved.source === 'flag') { console.log( - 'then restart Claude Code — or install plugins/claude-code for Tier A hooks.', + ` Requested host(s): ${resolved.ids.join(', ')}. Override recorded; envseal doctor reports what is actually detected.`, ); } + if (resolved.source === 'none') { + console.log(' No project host markers and this process is not an IDE.'); + console.log(' Wrote AGENTS.md only. Re-run from the IDE, or `envseal init --host cursor`.'); + } else if (resolved.ids.length > 0) { + console.log(` Wired host(s): ${resolved.ids.join(', ')} (${resolved.source})`); + } + for (const entry of wiring.hosts) { + if (entry.hint) { + for (const line of entry.hint.split('\n')) { + console.log(` ${line}`); + } + } + } + if (cursorEntry === undefined && !wiring.bareTerminal) { + console.log(' Reload MCP / restart the host, then run `envseal doctor`.'); + } else if (cursorWiring !== undefined && cursorWiring.mcp !== 'skipped' && wiring.hosts.length === 1) { + // Cursor entry already printed reloadHint. + } else if (wiring.bareTerminal && resolved.source === 'none') { + // Already printed the re-run hint. + } else if (wiring.hosts.some((h) => h.id !== 'cursor')) { + // Per-host hints already cover reload; keep a single closer. + } + if (resolved.ids.includes('claude-code')) { + console.log(' Claude Code: protocol connected (Tier B) via .mcp.json. Plugin = Tier A.'); + } } catch (error) { fail(json, error); } } + diff --git a/packages/cli/src/host-wiring/agents-md-content.ts b/packages/cli/src/host-wiring/agents-md-content.ts new file mode 100644 index 0000000..1a9299e --- /dev/null +++ b/packages/cli/src/host-wiring/agents-md-content.ts @@ -0,0 +1,72 @@ +/** + * Layer 1 instruction file shipped by `envseal init`. + * + * Keep this string identical to `plugins/generic/AGENTS.md`. The host-wiring + * test fails if they drift. Embedding (not reading plugins/ at runtime) is + * what makes published `@envseal/cli` able to write the file. + */ +export const AGENTS_MD_CONTENT = `# envseal — instructions for any coding agent + +This repository uses envseal to provision secrets. The secret values must never +appear in this chat, in your tool output, in files you write, or in commands you +run. Follow these rules without exception. + +## You must never + +- Read, write, or copy the contents of any \`.env\` or \`.env.*\` file. (\`.env.example\` + is the only exception: it holds placeholders, never values.) +- Run \`printenv\`, bare \`env\`, \`export -p\`, \`set\`, or \`echo $VAR\` / \`echo $KEY...\` + to inspect or display environment variables. +- Use \`cat\`, \`head\`, \`tail\`, \`less\`, \`grep\`, \`xxd\`, \`base64\`, \`sed\`, or any other + reader on a secrets file: \`*.pem\`, \`*.key\`, \`id_rsa*\`, \`credentials.json\`, + \`secrets.json\` / \`secrets.yaml\` / \`secrets.toml\`, \`.envseal/*\`. +- Ask the user to paste an API key, token, or connection string into the chat. +- Echo an environment variable into a transcript, log, diff, or tool result. + +## How to check which keys exist + +\`\`\`sh +envseal status # human-readable +envseal status --json # machine-readable; never contains values +\`\`\` + +Statuses are presence + metadata only (format-valid, length bucket, fingerprint, +last verified). There is no way to make envseal print a value. + +## How to provision a missing key + +\`\`\`sh +envseal ensure # prompts the user for every missing required key +envseal set KEY # prompts for a single key +\`\`\` + +Never ask the user to add a key to \`.env\` and tell you about it. Run +\`envseal ensure\` instead, and wait for its exit code. + +## How to run a command that needs secrets + +\`\`\`sh +envseal run -- +\`\`\` + +Secrets are injected only into that child process and its stdout/stderr are +redacted. Never run the command plain and never try to read the key yourself. + +## How to verify a key actually works + +\`\`\`sh +envseal verify # classified results: ok, auth_failed, rate_limited, ... +\`\`\` + +## How to ask the user what is wrong + +\`\`\`sh +envseal doctor # project root, detected host + tier, gitignore, missing keys +\`\`\` + +## Exit codes (for scripts) + +\`0\` ok · \`1\` required keys missing · \`2\` usage error · \`3\` cancelled · +\`4\` no interactive surface · \`5\` sink failure · \`6\` verification failed. +Use them; never parse human text for secrets. +`; diff --git a/packages/cli/src/host-wiring/agents-md.ts b/packages/cli/src/host-wiring/agents-md.ts new file mode 100644 index 0000000..8e0b7f4 --- /dev/null +++ b/packages/cli/src/host-wiring/agents-md.ts @@ -0,0 +1,59 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { AGENTS_MD_CONTENT } from './agents-md-content.js'; + +export type AgentsMdAction = 'created' | 'merged' | 'unchanged'; + +/** + * The envseal imperative: never read .env, use ensure/run instead of a paste. + * Doctor and init both use this so "instructions exist" is not just a filename. + */ +export function hasEnvsealImperative(text: string): boolean { + const neverEnv = /never/i.test(text) && /\.env/i.test(text); + const useEnsure = /envseal\s+ensure/i.test(text); + const useRun = /envseal\s+run/i.test(text); + return neverEnv && useEnsure && useRun; +} + +export function inspectAgentsMd(root: string): { + path: string; + exists: boolean; + instructions: 'ok' | 'missing'; +} { + const path = join(root, 'AGENTS.md'); + if (!existsSync(path)) { + return { path, exists: false, instructions: 'missing' }; + } + try { + const text = readFileSync(path, 'utf8'); + return { + path, + exists: true, + instructions: hasEnvsealImperative(text) ? 'ok' : 'missing', + }; + } catch { + return { path, exists: true, instructions: 'missing' }; + } +} + +/** + * Merge plugins/generic/AGENTS.md into project-root AGENTS.md. + * Creates the file, or appends an envseal section; never clobbers unrelated content. + */ +export function mergeAgentsMd(root: string): { action: AgentsMdAction; path: string } { + const path = join(root, 'AGENTS.md'); + if (!existsSync(path)) { + writeFileSync(path, AGENTS_MD_CONTENT, 'utf8'); + return { action: 'created', path }; + } + + const existing = readFileSync(path, 'utf8'); + if (hasEnvsealImperative(existing)) { + return { action: 'unchanged', path }; + } + + const trimmed = existing.replace(/\s+$/u, ''); + const next = `${trimmed}\n\n${AGENTS_MD_CONTENT}`; + writeFileSync(path, next, 'utf8'); + return { action: 'merged', path }; +} diff --git a/packages/cli/src/host-wiring/aider-conf.ts b/packages/cli/src/host-wiring/aider-conf.ts new file mode 100644 index 0000000..d69c888 --- /dev/null +++ b/packages/cli/src/host-wiring/aider-conf.ts @@ -0,0 +1,36 @@ +/** + * Aider config shipped by `envseal init --host aider`. + * + * Keep this string identical to `plugins/aider/.aider.conf.yml`. The host-wiring + * test fails if they drift. + */ +export const AIDER_CONF_YML = `# .aider.conf.yml — envseal for Aider (Tier C host, Tier-4 CLI binding) +# +# Aider renders every file it reads into the chat context. NEVER add \`.env\` +# or \`.env.*\` to the \`read\` list — that is exactly the leak path envseal exists +# to prevent. \`env.schema.jsonc\` and \`.env.example\` contain declarations and +# placeholders only and are safe to read. + +model: gpt-4o +edit-format: editor-diff + +read: + - env.schema.jsonc + - .env.example + +# Optional: run a command after every edit with secrets injected. +# auto-test: +# command: "../../.../envseal run -- pnpm test" + +# --- Tier-4 shell recipe (run from Aider's REPL) -------------------------- +# +# /run envseal status # which declared keys are present +# /run envseal ensure # prompt the user for every missing key +# /run envseal run -- pytest # run tests with secrets injected +# /run envseal verify # probe the keys end-to-end +# /run envseal doctor # report host + tier + config health +# +# \`envseal ensure\` and \`envseal run --\` are the only ways to obtain or use +# secret values inside Aider. Never ask the user to paste a key into the chat; +# never read \`.env\`; never \`echo $KEY\`. +`; diff --git a/packages/cli/src/host-wiring/aider.ts b/packages/cli/src/host-wiring/aider.ts new file mode 100644 index 0000000..db23a68 --- /dev/null +++ b/packages/cli/src/host-wiring/aider.ts @@ -0,0 +1,104 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { AIDER_CONF_YML } from './aider-conf.js'; +import type { McpWriteAction } from './mcp.js'; + +const AIDER_FILENAMES = [ + '.aider.conf.yml', + '.aider.conf.yaml', + 'aider.conf.yml', + 'aider.conf.yaml', + '.aider.conf.json', + 'aider.conf.json', +]; + +/** A `read:` list item that would dump `.env` into Aider's chat context. */ +const ENV_READ_ITEM = /^\s*-\s+['"]?\.env(?:\..*?)?['"]?\s*$/; + +export function aiderConfPath(root: string): string | undefined { + for (const name of AIDER_FILENAMES) { + const path = join(root, name); + if (existsSync(path)) return path; + } + return undefined; +} + +export function aiderReadListIncludesEnv(text: string): boolean { + return text.split(/\r?\n/).some((line) => ENV_READ_ITEM.test(line) && !/example/i.test(line)); +} + +function stripEnvFromReadList(text: string): string { + return text + .split(/\r?\n/) + .filter((line) => !(ENV_READ_ITEM.test(line) && !/example/i.test(line))) + .join('\n'); +} + +function ensureSafeReadEntries(text: string): string { + let next = stripEnvFromReadList(text); + if (!/^read:/m.test(next)) { + const trimmed = next.replace(/\s+$/u, ''); + return `${trimmed}\n\nread:\n - env.schema.jsonc\n - .env.example\n`; + } + if (!/env\.schema\.jsonc/.test(next)) { + next = next.replace(/^read:\s*$/m, 'read:\n - env.schema.jsonc'); + if (!/env\.schema\.jsonc/.test(next)) { + next = next.replace(/^read:/m, 'read:\n - env.schema.jsonc'); + } + } + if (!/\.env\.example/.test(next)) { + next = next.replace(/(env\.schema\.jsonc[^\n]*)/, '$1\n - .env.example'); + } + return next; +} + +export function inspectAiderConf(root: string): { + path: string | undefined; + envOnRead: boolean; + wired: boolean; + message: string; +} { + const path = aiderConfPath(root); + if (path === undefined) { + return { + path, + envOnRead: false, + wired: false, + message: 'No Aider config found. Run `envseal init --host aider` to write .aider.conf.yml.', + }; + } + const text = readFileSync(path, 'utf8'); + const envOnRead = aiderReadListIncludesEnv(text); + if (envOnRead) { + return { + path, + envOnRead: true, + wired: false, + message: `${path} lists .env under read: — Aider would paste secrets into chat. Re-run envseal init --host aider.`, + }; + } + return { + path, + envOnRead: false, + wired: true, + message: 'Aider config does not put .env on the read list.', + }; +} + +export function mergeAiderConf(root: string): { action: McpWriteAction; path: string } { + const existing = aiderConfPath(root); + const path = existing ?? join(root, '.aider.conf.yml'); + + if (!existsSync(path)) { + writeFileSync(path, AIDER_CONF_YML, 'utf8'); + return { action: 'created', path }; + } + + const text = readFileSync(path, 'utf8'); + const next = ensureSafeReadEntries(text); + if (next === text) { + return { action: 'unchanged', path }; + } + writeFileSync(path, next.endsWith('\n') ? next : `${next}\n`, 'utf8'); + return { action: 'merged', path }; +} diff --git a/packages/cli/src/host-wiring/apply.ts b/packages/cli/src/host-wiring/apply.ts new file mode 100644 index 0000000..25acbf2 --- /dev/null +++ b/packages/cli/src/host-wiring/apply.ts @@ -0,0 +1,235 @@ +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { mergeAiderConf } from './aider.js'; +import { mergeAgentsMd, type AgentsMdAction } from './agents-md.js'; +import { writeCodexProjectConfig } from './codex.js'; +import { writeContinueProjectFiles, continueSnippetYaml } from './continue.js'; +import { mergeCopilotSettings } from './copilot.js'; +import { writeCursorHostFiles, type CursorWiringResult } from './cursor.js'; +import { writeGooseMarker, gooseYamlSnippet } from './goose.js'; +import { mergeMcpServersFile, type McpWriteAction } from './mcp.js'; +import { mergeZedSettings } from './zed.js'; + +export type HostWiringEntry = { + id: string; + action: McpWriteAction | 'printed'; + path?: string; + hint: string; + extra?: Record; +}; + +export type ApplyWiringResult = { + agentsMd: { action: AgentsMdAction; path: string }; + hosts: HostWiringEntry[]; + cursor?: CursorWiringResult; + /** True when init wrote nothing host-specific besides AGENTS.md. */ + bareTerminal: boolean; +}; + +const RELOAD = 'Reload MCP / restart the host, then run `envseal doctor`.'; + +function mcpServersWrite( + id: string, + path: string, + relative: string, + platform: NodeJS.Platform, + extraHint?: string, +): HostWiringEntry { + const result = mergeMcpServersFile(path, platform); + const skipped = + result.action === 'skipped' + ? ` Could not merge ${relative} (invalid JSON). Fix the file and re-run envseal init.` + : ''; + return { + id, + action: result.action, + path: result.path, + hint: skipped || `${extraHint ?? ''} ${RELOAD}`.trim(), + }; +} + +export function applyHostWiring( + root: string, + hostIds: string[], + platform: NodeJS.Platform = process.platform, +): ApplyWiringResult { + const agentsMd = mergeAgentsMd(root); + const hosts: HostWiringEntry[] = []; + let cursor: CursorWiringResult | undefined; + + const unique = [...new Set(hostIds)]; + const writesMcpHost = unique.some((id) => + [ + 'cursor', + 'claude-code', + 'windsurf', + 'cline', + 'zed', + 'jetbrains', + 'copilot', + 'continue', + 'codex', + 'goose', + 'aider', + ].includes(id), + ); + + for (const id of unique) { + switch (id) { + case 'cursor': { + cursor = writeCursorHostFiles(root, platform); + hosts.push({ + id, + action: cursor.mcp, + path: cursor.mcpPath, + hint: + cursor.mcp === 'skipped' + ? 'Could not merge .cursor/mcp.json (invalid JSON). Fix the file and re-run envseal init.' + : cursor.reloadHint, + extra: { mcp: cursor.mcp, rules: cursor.rules, rulesPath: cursor.rulesPath }, + }); + break; + } + case 'claude-code': { + mkdirSync(join(root, '.claude'), { recursive: true }); + hosts.push( + mcpServersWrite( + id, + join(root, '.mcp.json'), + '.mcp.json', + platform, + 'Wrote project .mcp.json (Tier B protocol). Restart Claude Code so it picks up envseal-mcp. Install plugins/claude-code for Tier A hooks — doctor reports A only when hooks are visible.', + ), + ); + break; + } + case 'windsurf': { + hosts.push( + mcpServersWrite( + id, + join(root, '.windsurf', 'mcp_config.json'), + '.windsurf/mcp_config.json', + platform, + '[VERIFY] Windsurf MCP schema has shifted across releases.', + ), + ); + break; + } + case 'cline': { + hosts.push( + mcpServersWrite( + id, + join(root, '.cline', 'mcp_settings.json'), + '.cline/mcp_settings.json', + platform, + '[VERIFY] Cline MCP schema.', + ), + ); + break; + } + case 'zed': { + const result = mergeZedSettings(root, platform); + hosts.push({ + id, + action: result.action, + path: result.path, + hint: + result.action === 'skipped' + ? 'Could not merge .zed/settings.json (invalid JSON). Fix the file and re-run envseal init. [VERIFY]' + : `[VERIFY] Zed MCP key shape. ${RELOAD}`, + }); + break; + } + case 'jetbrains': { + hosts.push( + mcpServersWrite( + id, + join(root, '.idea', 'mcp.json'), + '.idea/mcp.json', + platform, + '[VERIFY] JetBrains MCP location varies by product.', + ), + ); + break; + } + case 'copilot': { + const result = mergeCopilotSettings(root, platform); + hosts.push({ + id, + action: result.action, + path: result.path, + hint: + result.action === 'skipped' + ? 'Could not merge .vscode/settings.json (invalid JSON). Fix the file and re-run envseal init. [VERIFY]' + : `[VERIFY] github.copilot.mcp schema. ${RELOAD}`, + }); + break; + } + case 'continue': { + const result = writeContinueProjectFiles(root, platform); + hosts.push({ + id, + action: result.action, + path: result.path, + hint: `${result.printOnlyHint}\n\nMerge into ~/.continue/config.yaml:\n${continueSnippetYaml(platform)}`, + }); + break; + } + case 'codex': { + const result = writeCodexProjectConfig(root, platform); + hosts.push({ + id, + action: result.action, + path: result.path, + hint: `[VERIFY] Codex may still read ~/.codex/config.toml; envseal does not write $HOME. ${RELOAD}`, + }); + break; + } + case 'goose': { + const result = writeGooseMarker(root); + hosts.push({ + id, + action: 'printed', + path: result.path, + hint: `Goose is not OOTB. ${result.addHint}\n\nOr merge (unverified yaml):\n${gooseYamlSnippet(platform)}`, + }); + break; + } + case 'aider': { + const result = mergeAiderConf(root); + hosts.push({ + id, + action: result.action, + path: result.path, + hint: 'Merged Aider config so .env is not on the read list. Use /run envseal ensure.', + }); + break; + } + case 'generic': + case 'unknown': + case 'openhands': + hosts.push({ + id, + action: 'printed', + hint: + id === 'openhands' + ? 'OpenHands is deployment-dependent (binary inside sandbox, TTY for ensure). Layer 1 AGENTS.md is the working path.' + : 'Layer 1 only (AGENTS.md). Any agent that reads instruction files can run envseal ensure / envseal run --.', + }); + break; + default: + hosts.push({ + id, + action: 'printed', + hint: 'Unknown host: Layer 1 AGENTS.md only. Re-run from the IDE or `envseal init --host `.', + }); + } + } + + return { + agentsMd, + hosts, + cursor, + bareTerminal: !writesMcpHost, + }; +} diff --git a/packages/cli/src/host-wiring/codex.ts b/packages/cli/src/host-wiring/codex.ts new file mode 100644 index 0000000..d7d7011 --- /dev/null +++ b/packages/cli/src/host-wiring/codex.ts @@ -0,0 +1,68 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { mcpLaunch, type McpInspection, type McpWriteAction } from './mcp.js'; + +export function codexTomlBlock(platform: NodeJS.Platform = process.platform): string { + const launch = mcpLaunch(platform); + const args = launch.args.map((a) => `"${a}"`).join(', '); + return `[mcp_servers.envseal-mcp] +command = "${launch.command}" +args = [${args}] +`; +} + +export function writeCodexProjectConfig( + root: string, + platform: NodeJS.Platform = process.platform, +): { action: McpWriteAction; path: string } { + const path = join(root, '.codex', 'config.toml'); + const block = `# envseal MCP — [VERIFY] Codex schema is still moving. Prefer project +# .codex/ over ~/.codex/config.toml (global cwd is $HOME). +${codexTomlBlock(platform)}`; + + if (!existsSync(path)) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, block, 'utf8'); + return { action: 'created', path }; + } + + const existing = readFileSync(path, 'utf8'); + if (/mcp_servers\.envseal-mcp|envseal-mcp/.test(existing)) { + return { action: 'unchanged', path }; + } + + const trimmed = existing.replace(/\s+$/u, ''); + writeFileSync(path, `${trimmed}\n\n${block}`, 'utf8'); + return { action: 'merged', path }; +} + +export function inspectCodexProject(root: string): McpInspection { + const path = join(root, '.codex', 'config.toml'); + const hint = + 'Run `envseal init` to write project .codex/config.toml. [VERIFY] Codex may still only read ~/.codex/config.toml — envseal does not write $HOME.'; + + if (!existsSync(path)) { + return { + wired: false, + status: 'absent', + commandOk: null, + message: `.codex/config.toml is missing. ${hint}`, + }; + } + + const text = readFileSync(path, 'utf8'); + if (!/envseal-mcp/.test(text)) { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `.codex/config.toml has no envseal-mcp. ${hint}`, + }; + } + return { + wired: true, + status: 'wired', + commandOk: null, + message: 'Project .codex/config.toml names envseal-mcp. [VERIFY: Codex may ignore project files.]', + }; +} diff --git a/packages/cli/src/host-wiring/continue.ts b/packages/cli/src/host-wiring/continue.ts new file mode 100644 index 0000000..6880a01 --- /dev/null +++ b/packages/cli/src/host-wiring/continue.ts @@ -0,0 +1,64 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { mcpLaunch, type McpInspection, type McpWriteAction } from './mcp.js'; + +export function continueSnippetYaml(platform: NodeJS.Platform = process.platform): string { + const launch = mcpLaunch(platform); + const args = launch.args.map((a) => `"${a}"`).join(', '); + return `mcpServers: + - name: envseal-mcp + command: ${launch.command} + args: [${args}] +`; +} + +export function writeContinueProjectFiles( + root: string, + platform: NodeJS.Platform = process.platform, +): { action: McpWriteAction; path: string; printOnlyHint: string } { + const dir = join(root, '.continue'); + mkdirSync(dir, { recursive: true }); + const path = join(dir, 'config.yaml'); + const snippet = continueSnippetYaml(platform); + const printOnlyHint = + 'Continue loads MCP from ~/.continue/config.yaml (global), not this project file. Merge the printed block into the global config; envseal does not write $HOME files. [VERIFY]'; + + if (!existsSync(path)) { + const body = `# Project copy of the envseal MCP snippet. Continue currently reads +# ~/.continue/config.yaml — merge the mcpServers block there. Do not copy this +# into $HOME from envseal init; this file exists so doctor can see the host. +# +# [VERIFY: recent Continue builds moved to a new HUB config schema; if a +# top-level mcpServers list is not accepted, use experimental.mcpServers.] + +${snippet}`; + writeFileSync(path, body, 'utf8'); + return { action: 'created', path, printOnlyHint }; + } + + const existing = readFileSync(path, 'utf8'); + if (/envseal-mcp/.test(existing) && /@envseal\/mcp-server|npx/.test(existing)) { + return { action: 'unchanged', path, printOnlyHint }; + } + if (/envseal-mcp/.test(existing)) { + return { action: 'unchanged', path, printOnlyHint }; + } + + const trimmed = existing.replace(/\s+$/u, ''); + writeFileSync(path, `${trimmed}\n\n${snippet}`, 'utf8'); + return { action: 'merged', path, printOnlyHint }; +} + +export function inspectContinueProject(root: string): McpInspection { + const path = join(root, '.continue', 'config.yaml'); + const hasSnippet = existsSync(path) && /envseal-mcp/.test(readFileSync(path, 'utf8')); + // Continue's documented MCP file is ~/.continue/config.yaml. envseal never + // writes $HOME, so project MCP is not OOTB regardless of the snippet file. + return { + wired: false, + status: hasSnippet ? 'missing' : 'absent', + commandOk: null, + message: + 'Continue is not OOTB: merge the envseal mcpServers block into ~/.continue/config.yaml (envseal does not write $HOME). Project .continue/ is a detection marker + copy-paste snippet. [VERIFY]', + }; +} diff --git a/packages/cli/src/host-wiring/copilot.ts b/packages/cli/src/host-wiring/copilot.ts new file mode 100644 index 0000000..161719a --- /dev/null +++ b/packages/cli/src/host-wiring/copilot.ts @@ -0,0 +1,129 @@ +import { existsSync, mkdirSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { + ENVSEAL_MCP_SERVER_NAME, + isRecord, + mcpLaunch, + parseJsonObject, + writeJson, + isEmptyEnvsealStub, + isStockNpxLaunch, + looksLikeEnvsealServer, + probeVersion, + type McpInspection, + type McpWriteAction, +} from './mcp.js'; + +function asServerList(value: unknown): unknown[] | undefined { + if (value === undefined) return undefined; + if (!Array.isArray(value)) return undefined; + return value; +} + +function entryName(entry: unknown): string | undefined { + if (!isRecord(entry)) return undefined; + if (typeof entry.name === 'string') return entry.name; + return undefined; +} + +export function mergeCopilotSettings( + root: string, + platform: NodeJS.Platform = process.platform, +): { action: McpWriteAction; path: string } { + const path = join(root, '.vscode', 'settings.json'); + const launch = { name: ENVSEAL_MCP_SERVER_NAME, ...mcpLaunch(platform) }; + + if (!existsSync(path)) { + mkdirSync(dirname(path), { recursive: true }); + writeJson(path, { 'github.copilot.mcp': [launch] }); + return { action: 'created', path }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { action: 'skipped', path }; + } + + const existing = asServerList(parsed['github.copilot.mcp']); + if (parsed['github.copilot.mcp'] !== undefined && existing === undefined) { + return { action: 'skipped', path }; + } + + const list = existing === undefined ? [] : [...existing]; + const index = list.findIndex((item) => entryName(item) === ENVSEAL_MCP_SERVER_NAME); + + if (index === -1) { + list.push(launch); + writeJson(path, { ...parsed, 'github.copilot.mcp': list }); + return { action: 'merged', path }; + } + + const current = list[index]; + if (isEmptyEnvsealStub(current) || isStockNpxLaunch(current)) { + if (isStockNpxLaunch(current) && isRecord(current) && current.command === launch.command) { + return { action: 'unchanged', path }; + } + list[index] = isRecord(current) ? { ...current, ...launch } : launch; + writeJson(path, { ...parsed, 'github.copilot.mcp': list }); + return { action: 'merged', path }; + } + + return { action: 'unchanged', path }; +} + +export function inspectCopilotSettings( + root: string, + options: { probe?: boolean; platform?: NodeJS.Platform } = {}, +): McpInspection { + const path = join(root, '.vscode', 'settings.json'); + const hint = + 'Run `envseal init` to merge github.copilot.mcp with envseal-mcp (npx @envseal/mcp-server). [VERIFY]'; + + if (!existsSync(path)) { + return { + wired: false, + status: 'absent', + commandOk: null, + message: `.vscode/settings.json is missing. ${hint}`, + }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { + wired: false, + status: 'unreadable', + commandOk: null, + message: `.vscode/settings.json is not valid JSON. ${hint}`, + }; + } + + const list = asServerList(parsed['github.copilot.mcp']); + if (list === undefined || list.length === 0) { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `.vscode/settings.json has no github.copilot.mcp envseal entry. ${hint}`, + }; + } + + const entry = list.find((item) => entryName(item) === ENVSEAL_MCP_SERVER_NAME); + if (entry === undefined || isEmptyEnvsealStub(entry) || !looksLikeEnvsealServer(entry)) { + return { + wired: false, + status: entry === undefined ? 'missing' : 'stub', + commandOk: null, + message: `.vscode/settings.json github.copilot.mcp has no working envseal-mcp. ${hint}`, + }; + } + + const rec = entry as Record; + const commandOk = options.probe === true ? probeVersion(rec) : null; + let message = 'Copilot MCP is wired (project .vscode/settings.json github.copilot.mcp). [VERIFY]'; + if (commandOk === false) { + message = + 'Copilot MCP is configured, but the launch command did not report a version. Run `envseal init`. [VERIFY]'; + } + return { wired: true, status: 'wired', commandOk, message }; +} diff --git a/packages/cli/src/host-wiring/cursor-rules.ts b/packages/cli/src/host-wiring/cursor-rules.ts new file mode 100644 index 0000000..b86c657 --- /dev/null +++ b/packages/cli/src/host-wiring/cursor-rules.ts @@ -0,0 +1,30 @@ +/** + * Advisory Cursor rule file shipped by `envseal init`. + * + * Keep this string identical to `plugins/cursor/rules/envseal.mdc`. The + * cursor-wiring test fails if they drift. Embedding (not reading plugins/ at + * runtime) is what makes published `@envseal/cli` able to write the file. + */ +export const CURSOR_RULES_MDC = `--- +description: envseal — never read .env, never echo secrets; use env_describe/env_request instead. +alwaysApply: true +--- + +Cursor rules are advisory, not enforced. Treat these as hard rules regardless. + +- Never read, write, or print the contents of \`.env\` or any \`.env.*\` file (\`.env.example\` is the only exception — it contains placeholders, never values). +- Never run \`printenv\`, bare \`env\`, \`export -p\`, \`set\`, \`env | grep ...\`, or \`echo $VAR\` / \`echo $KEY...\` to inspect or display environment variables. Every one of these puts secret values into the transcript. +- Never \`cat\`, \`head\`, \`tail\`, \`less\`, \`grep\`, \`xxd\`, or \`base64\` a secrets file (\`*.pem\`, \`*.key\`, \`credentials.json\`, \`secrets.json\`, \`.envseal/*\`). +- Never ask the user to paste an API key into the chat. + +Instead, use the envseal broker via MCP: + +- \`env_describe\` — read-only status of the declared keys (present, format-valid, last verified). It never returns values and there is no way to make it do so. +- \`env_request\` — collect the missing keys from the user through a secure prompt. It returns a ticket, never a value; follow up with \`env_await\`. +- \`env_declare\` — declare a key this project needs, with format and provider metadata. +- \`env_verify\` — test that a key actually works (classified result only). +- \`env_use\` — run a command with secrets injected into the child process; output is redacted. +- \`env_revoke\` — remove a key and get the rotation URL. + +If a required key is missing, \`env_request\` it. Never read \`.env\` to find it, and never print it back. +`; diff --git a/packages/cli/src/host-wiring/cursor.ts b/packages/cli/src/host-wiring/cursor.ts new file mode 100644 index 0000000..dcf81f3 --- /dev/null +++ b/packages/cli/src/host-wiring/cursor.ts @@ -0,0 +1,83 @@ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { CURSOR_RULES_MDC } from './cursor-rules.js'; +import { + inspectMcpServersFile, + mcpLaunch, + mcpSnippetJson, + mergeMcpServersFile, + type McpInspection, + type McpLaunch, + type McpWriteAction, +} from './mcp.js'; + +export { + ENVSEAL_MCP_PACKAGE, + ENVSEAL_MCP_SERVER_NAME, + isEmptyEnvsealStub, + isStockNpxLaunch, +} from './mcp.js'; + +export type CursorMcpLaunch = McpLaunch; +export type CursorMcpWriteAction = McpWriteAction; +export type CursorRulesWriteAction = 'created' | 'unchanged'; +export type CursorMcpStatus = McpInspection['status']; +export type CursorMcpInspection = McpInspection; + +export type CursorWiringResult = { + mcp: CursorMcpWriteAction; + rules: CursorRulesWriteAction; + mcpPath: string; + rulesPath: string; + /** Human one-liner: reload MCP. Empty when mcp write was skipped. */ + reloadHint: string; +}; + +const RELOAD_HINT = 'Reload MCP in Settings → MCP so Cursor picks up envseal-mcp.'; + +export function cursorMcpLaunch(platform: NodeJS.Platform = process.platform): CursorMcpLaunch { + return mcpLaunch(platform); +} + +export function cursorMcpSnippetJson(platform: NodeJS.Platform = process.platform): string { + return mcpSnippetJson(platform); +} + +export function writeCursorMcpJson( + root: string, + platform: NodeJS.Platform = process.platform, +): { action: CursorMcpWriteAction; path: string } { + return mergeMcpServersFile(join(root, '.cursor', 'mcp.json'), platform); +} + +export function writeCursorRules(root: string): { action: CursorRulesWriteAction; path: string } { + const path = join(root, '.cursor', 'rules', 'envseal.mdc'); + if (existsSync(path)) { + return { action: 'unchanged', path }; + } + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, CURSOR_RULES_MDC, 'utf8'); + return { action: 'created', path }; +} + +export function writeCursorHostFiles( + root: string, + platform: NodeJS.Platform = process.platform, +): CursorWiringResult { + const mcp = writeCursorMcpJson(root, platform); + const rules = writeCursorRules(root); + return { + mcp: mcp.action, + rules: rules.action, + mcpPath: mcp.path, + rulesPath: rules.path, + reloadHint: mcp.action === 'skipped' ? '' : RELOAD_HINT, + }; +} + +export function inspectCursorMcp( + root: string, + options: { probe?: boolean; platform?: NodeJS.Platform } = {}, +): CursorMcpInspection { + return inspectMcpServersFile(join(root, '.cursor', 'mcp.json'), '.cursor/mcp.json', options); +} diff --git a/packages/cli/src/host-wiring/goose.ts b/packages/cli/src/host-wiring/goose.ts new file mode 100644 index 0000000..5f703d6 --- /dev/null +++ b/packages/cli/src/host-wiring/goose.ts @@ -0,0 +1,66 @@ +import { existsSync, mkdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { mcpLaunch, type McpInspection, type McpWriteAction } from './mcp.js'; + +export function gooseYamlSnippet(platform: NodeJS.Platform = process.platform): string { + const launch = mcpLaunch(platform); + const args = launch.args.map((a) => `"${a}"`).join(', '); + return `mcp: + servers: + envseal-mcp: + cmd: ${launch.command} + args: [${args}] +`; +} + +export function gooseAddHint(platform: NodeJS.Platform = process.platform): string { + const launch = mcpLaunch(platform); + const args = launch.args.join(' '); + return `goose mcp add envseal-mcp -- ${launch.command} ${args} # [VERIFY: exact flags for your build]`; +} + +/** + * Goose is print-only: do not invent a verified project schema. + * Create `.goose/` so doctor can label the host; MCP stays unwired until the + * user runs the printed CLI / yaml themselves. + */ +export function writeGooseMarker(root: string): { + action: McpWriteAction; + path: string; + addHint: string; + yamlSnippet: string; +} { + const dir = join(root, '.goose'); + const existed = existsSync(dir); + mkdirSync(dir, { recursive: true }); + return { + action: existed ? 'unchanged' : 'created', + path: dir, + addHint: gooseAddHint(), + yamlSnippet: gooseYamlSnippet(), + }; +} + +export function inspectGooseProject(root: string): McpInspection { + const files = [join(root, 'goose.config.yaml'), join(root, '.goose', 'config.yaml')]; + for (const path of files) { + if (!existsSync(path)) continue; + const text = readFileSync(path, 'utf8'); + if (/envseal-mcp/.test(text)) { + return { + wired: true, + status: 'wired', + commandOk: null, + message: `Goose config names envseal-mcp (${path}). [VERIFY]`, + }; + } + } + + return { + wired: false, + status: 'missing', + commandOk: null, + message: + 'Goose is not OOTB: run `goose mcp add` (see envseal init output) or merge the yaml snippet. envseal does not write ~/.config/goose/. [VERIFY]', + }; +} diff --git a/packages/cli/src/host-wiring/inspect.ts b/packages/cli/src/host-wiring/inspect.ts new file mode 100644 index 0000000..e534ad1 --- /dev/null +++ b/packages/cli/src/host-wiring/inspect.ts @@ -0,0 +1,144 @@ +import { join } from 'node:path'; +import { inspectAiderConf } from './aider.js'; +import { inspectAgentsMd } from './agents-md.js'; +import { inspectCodexProject } from './codex.js'; +import { inspectContinueProject } from './continue.js'; +import { inspectCopilotSettings } from './copilot.js'; +import { inspectCursorMcp } from './cursor.js'; +import { inspectGooseProject } from './goose.js'; +import { inspectMcpServersFile, mcpWiringState, type McpInspection } from './mcp.js'; +import { inspectZedSettings } from './zed.js'; + +export type AgentWiringMcp = 'ok' | 'missing' | 'spawn_failed'; +export type AgentWiringInstructions = 'ok' | 'missing'; + +export type AgentWiring = { + mcp: AgentWiringMcp; + instructions: AgentWiringInstructions; +}; + +export type PrimaryHostInspection = { + wiring: AgentWiring; + mcp?: McpInspection; + /** Hosts where MCP is expected in a project file. */ + mcpRequired: boolean; + /** Documented as print-only / not OOTB even after init. */ + notOotb: boolean; + /** Aider: `.env` appears on the `read:` list. */ + aiderUnsafe: boolean; + message: string; +}; + +const MCP_REQUIRED = new Set([ + 'cursor', + 'claude-code', + 'windsurf', + 'cline', + 'zed', + 'jetbrains', + 'copilot', + 'continue', + 'codex', + 'goose', +]); + +const NOT_OOTB = new Set(['continue', 'goose']); + +function inspectPrimaryMcp( + root: string, + hostId: string, + options: { probe?: boolean; platform?: NodeJS.Platform }, +): McpInspection | undefined { + switch (hostId) { + case 'cursor': + return inspectCursorMcp(root, options); + case 'claude-code': + return inspectMcpServersFile(join(root, '.mcp.json'), '.mcp.json', options); + case 'windsurf': + return inspectMcpServersFile( + join(root, '.windsurf', 'mcp_config.json'), + '.windsurf/mcp_config.json', + options, + ); + case 'cline': + return inspectMcpServersFile( + join(root, '.cline', 'mcp_settings.json'), + '.cline/mcp_settings.json', + options, + ); + case 'zed': + return inspectZedSettings(root, options); + case 'jetbrains': + return inspectMcpServersFile(join(root, '.idea', 'mcp.json'), '.idea/mcp.json', options); + case 'copilot': + return inspectCopilotSettings(root, options); + case 'continue': + return inspectContinueProject(root); + case 'codex': + return inspectCodexProject(root); + case 'goose': + return inspectGooseProject(root); + default: + return undefined; + } +} + +export function inspectPrimaryHostWiring( + root: string, + hostId: string, + options: { probe?: boolean; platform?: NodeJS.Platform } = {}, +): PrimaryHostInspection { + const instructions = inspectAgentsMd(root).instructions; + const mcpRequired = MCP_REQUIRED.has(hostId); + const notOotb = NOT_OOTB.has(hostId); + + if (hostId === 'aider') { + const aider = inspectAiderConf(root); + return { + wiring: { mcp: 'ok', instructions }, + mcpRequired: false, + notOotb: false, + aiderUnsafe: !aider.wired, + message: aider.message, + }; + } + + if (!mcpRequired) { + return { + wiring: { mcp: 'ok', instructions }, + mcpRequired: false, + notOotb: false, + aiderUnsafe: false, + message: + instructions === 'ok' + ? 'Layer 1 instructions present (AGENTS.md).' + : 'AGENTS.md is missing the envseal imperative (never read .env; use envseal ensure / envseal run). Run `envseal init`.', + }; + } + + const inspection = inspectPrimaryMcp(root, hostId, options) ?? { + wired: false, + status: 'missing' as const, + commandOk: null, + message: `No project MCP config for host ${hostId}. Run \`envseal init\`.`, + }; + + return { + wiring: { + mcp: mcpWiringState(inspection), + instructions, + }, + mcp: inspection, + mcpRequired: true, + notOotb, + aiderUnsafe: false, + message: inspection.message, + }; +} + +export function wiringFailsDoctor(inspection: PrimaryHostInspection): boolean { + if (inspection.mcpRequired && inspection.wiring.mcp !== 'ok') return true; + if (inspection.wiring.instructions === 'missing') return true; + if (inspection.aiderUnsafe) return true; + return false; +} diff --git a/packages/cli/src/host-wiring/mcp.ts b/packages/cli/src/host-wiring/mcp.ts new file mode 100644 index 0000000..8c12ed3 --- /dev/null +++ b/packages/cli/src/host-wiring/mcp.ts @@ -0,0 +1,269 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; +import { spawnSync } from 'node:child_process'; + +export const ENVSEAL_MCP_PACKAGE = '@envseal/mcp-server'; +export const ENVSEAL_MCP_SERVER_NAME = 'envseal-mcp'; +export const NPX_ARGS = ['-y', ENVSEAL_MCP_PACKAGE] as const; + +export type McpLaunch = { + command: string; + args: string[]; +}; + +export type McpWriteAction = 'created' | 'merged' | 'unchanged' | 'skipped'; +export type McpStatus = 'absent' | 'unreadable' | 'missing' | 'stub' | 'wired'; + +export type McpInspection = { + wired: boolean; + status: McpStatus; + message: string; + /** null when the launch command was not probed (npx is not side-effect free). */ + commandOk: boolean | null; +}; + +/** + * Launch argv a host can spawn without a global `envseal-mcp` on PATH. + * Project MCP uses the workspace as cwd — never bake `--project` in. + */ +export function mcpLaunch(platform: NodeJS.Platform = process.platform): McpLaunch { + return { + command: platform === 'win32' ? 'npx.cmd' : 'npx', + args: [...NPX_ARGS], + }; +} + +export function mcpSnippetJson(platform: NodeJS.Platform = process.platform): string { + const launch = mcpLaunch(platform); + return JSON.stringify({ + mcpServers: { [ENVSEAL_MCP_SERVER_NAME]: launch }, + }); +} + +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +export function argsList(value: unknown): string[] | undefined { + if (value === undefined) return undefined; + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) return undefined; + return value as string[]; +} + +/** Old shipped stub: `envseal-mcp` with no args. Host launchers do not search node_modules/.bin. */ +export function isEmptyEnvsealStub(entry: unknown): boolean { + if (!isRecord(entry)) return true; + const command = entry.command; + if (typeof command !== 'string' || command.trim() === '') return true; + if (command !== 'envseal-mcp') return false; + const args = argsList(entry.args); + return args === undefined || args.length === 0; +} + +/** Our npx snippet, either platform variant, and nothing else in command/args. */ +export function isStockNpxLaunch(entry: unknown): boolean { + if (!isRecord(entry)) return false; + const command = entry.command; + if (command !== 'npx' && command !== 'npx.cmd') return false; + const args = argsList(entry.args); + return ( + args !== undefined && args.length === NPX_ARGS.length && NPX_ARGS.every((a, i) => a === args[i]) + ); +} + +/** True when an entry would actually start @envseal/mcp-server (npx or a non-empty command). */ +export function looksLikeEnvsealServer(entry: unknown): boolean { + if (entry === undefined || isEmptyEnvsealStub(entry)) return false; + if (!isRecord(entry)) return false; + const command = entry.command; + if (typeof command !== 'string' || command.trim() === '') return false; + if (isStockNpxLaunch(entry)) return true; + const joined = `${command} ${(argsList(entry.args) ?? []).join(' ')}`; + return /@envseal\/mcp-server|envseal-mcp/i.test(joined); +} + +export function nextEnvsealEntry( + current: unknown, + launch: McpLaunch, +): McpLaunch | Record | null { + if (current === undefined || isEmptyEnvsealStub(current)) { + return launch; + } + if (isStockNpxLaunch(current) && isRecord(current)) { + if (current.command === launch.command) return null; + return { ...current, command: launch.command, args: launch.args }; + } + return null; +} + +export function parseJsonObject(text: string): Record | null { + try { + const parsed: unknown = JSON.parse(text); + return isRecord(parsed) ? parsed : null; + } catch { + return null; + } +} + +export function writeJson(path: string, value: unknown): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8'); +} + +/** + * Merge envseal-mcp into a file whose top-level key is `mcpServers`. + * Never writes user-global configs; the caller passes a project path. + */ +export function mergeMcpServersFile( + path: string, + platform: NodeJS.Platform = process.platform, +): { action: McpWriteAction; path: string } { + const launch = mcpLaunch(platform); + + if (!existsSync(path)) { + writeJson(path, { mcpServers: { [ENVSEAL_MCP_SERVER_NAME]: launch } }); + return { action: 'created', path }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { action: 'skipped', path }; + } + + const existingServers = parsed.mcpServers; + if (existingServers !== undefined && !isRecord(existingServers)) { + return { action: 'skipped', path }; + } + + const servers: Record = + existingServers === undefined ? {} : { ...existingServers }; + const next = nextEnvsealEntry(servers[ENVSEAL_MCP_SERVER_NAME], launch); + if (next === null) { + return { action: 'unchanged', path }; + } + + servers[ENVSEAL_MCP_SERVER_NAME] = next; + writeJson(path, { ...parsed, mcpServers: servers }); + return { action: 'merged', path }; +} + +export function classifyEntry(entry: unknown): 'missing' | 'stub' | 'wired' { + if (entry === undefined) return 'missing'; + if (isEmptyEnvsealStub(entry)) return 'stub'; + if (!isRecord(entry)) return 'stub'; + const command = entry.command; + if (typeof command !== 'string' || command.trim() === '') return 'stub'; + return 'wired'; +} + +/** + * `--version` is side-effect free on the envseal-mcp binary. `npx -y` is not + * (it may hit the network), so the default snippet is not probed. + */ +export function shouldProbeLaunch(entry: Record): boolean { + const command = entry.command; + if (typeof command !== 'string') return false; + if (command === 'npx' || command === 'npx.cmd') return false; + return true; +} + +export function probeVersion(entry: Record): boolean | null { + if (!shouldProbeLaunch(entry)) return null; + const command = entry.command; + if (typeof command !== 'string') return null; + const args = argsList(entry.args) ?? []; + const result = spawnSync(command, [...args, '--version'], { + encoding: 'utf8', + timeout: 5000, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + }); + if (result.error) return false; + if (result.status !== 0) return false; + const out = `${result.stdout ?? ''}${result.stderr ?? ''}`; + return /envseal-mcp/i.test(out); +} + +function initHint(platform: NodeJS.Platform, label: string): string { + return `Run \`envseal init\` to write it, or merge ${mcpSnippetJson(platform)} into ${label}.`; +} + +export function inspectMcpServersFile( + path: string, + label: string, + options: { probe?: boolean; platform?: NodeJS.Platform } = {}, +): McpInspection { + const platform = options.platform ?? process.platform; + const hint = initHint(platform, label); + + if (!existsSync(path)) { + return { + wired: false, + status: 'absent', + commandOk: null, + message: `${label} is missing. ${hint}`, + }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { + wired: false, + status: 'unreadable', + commandOk: null, + message: `${label} is not valid JSON. ${hint}`, + }; + } + + const servers = parsed.mcpServers; + if (servers === undefined || (isRecord(servers) && Object.keys(servers).length === 0)) { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `${label} has no envseal-mcp (empty mcpServers). ${hint}`, + }; + } + if (!isRecord(servers)) { + return { + wired: false, + status: 'unreadable', + commandOk: null, + message: `${label} mcpServers is not an object. ${hint}`, + }; + } + + const entry = servers[ENVSEAL_MCP_SERVER_NAME]; + const kind = classifyEntry(entry); + if (kind === 'missing') { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `${label} has no envseal-mcp. ${hint}`, + }; + } + if (kind === 'stub') { + return { + wired: false, + status: 'stub', + commandOk: null, + message: `${label} envseal-mcp is the empty envseal-mcp stub (not on PATH for the host). ${hint}`, + }; + } + + const rec = entry as Record; + const commandOk = options.probe === true ? probeVersion(rec) : null; + let message = `MCP is wired (${label}).`; + if (commandOk === false) { + message = `MCP is configured in ${label}, but the launch command did not report a version. Run \`envseal init\` if the host cannot connect.`; + } + return { wired: true, status: 'wired', commandOk, message }; +} + +/** Map an inspection to the doctor `agentWiring.mcp` field. */ +export function mcpWiringState(inspection: McpInspection): 'ok' | 'missing' | 'spawn_failed' { + if (inspection.commandOk === false) return 'spawn_failed'; + if (inspection.wired) return 'ok'; + return 'missing'; +} diff --git a/packages/cli/src/host-wiring/zed.ts b/packages/cli/src/host-wiring/zed.ts new file mode 100644 index 0000000..75a7170 --- /dev/null +++ b/packages/cli/src/host-wiring/zed.ts @@ -0,0 +1,126 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { + ENVSEAL_MCP_SERVER_NAME, + isRecord, + mcpLaunch, + nextEnvsealEntry, + parseJsonObject, + writeJson, + classifyEntry, + probeVersion, + type McpInspection, + type McpWriteAction, +} from './mcp.js'; + +function zedHint(platform: NodeJS.Platform): string { + const launch = mcpLaunch(platform); + return `Run \`envseal init\` to merge { "mcp": { "${ENVSEAL_MCP_SERVER_NAME}": ${JSON.stringify(launch)} } } into .zed/settings.json. [VERIFY]`; +} + +export function mergeZedSettings( + root: string, + platform: NodeJS.Platform = process.platform, +): { action: McpWriteAction; path: string } { + const path = join(root, '.zed', 'settings.json'); + const launch = mcpLaunch(platform); + + if (!existsSync(path)) { + writeJson(path, { mcp: { [ENVSEAL_MCP_SERVER_NAME]: launch } }); + return { action: 'created', path }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { action: 'skipped', path }; + } + + const existingMcp = parsed.mcp; + if (existingMcp !== undefined && !isRecord(existingMcp)) { + return { action: 'skipped', path }; + } + + const mcp: Record = existingMcp === undefined ? {} : { ...existingMcp }; + const next = nextEnvsealEntry(mcp[ENVSEAL_MCP_SERVER_NAME], launch); + if (next === null) { + return { action: 'unchanged', path }; + } + + mcp[ENVSEAL_MCP_SERVER_NAME] = next; + writeJson(path, { ...parsed, mcp }); + return { action: 'merged', path }; +} + +export function inspectZedSettings( + root: string, + options: { probe?: boolean; platform?: NodeJS.Platform } = {}, +): McpInspection { + const platform = options.platform ?? process.platform; + const path = join(root, '.zed', 'settings.json'); + const hint = zedHint(platform); + + if (!existsSync(path)) { + return { + wired: false, + status: 'absent', + commandOk: null, + message: `.zed/settings.json is missing. ${hint}`, + }; + } + + const parsed = parseJsonObject(readFileSync(path, 'utf8')); + if (parsed === null) { + return { + wired: false, + status: 'unreadable', + commandOk: null, + message: `.zed/settings.json is not valid JSON. ${hint}`, + }; + } + + const mcp = parsed.mcp; + if (mcp === undefined || (isRecord(mcp) && Object.keys(mcp).length === 0)) { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `.zed/settings.json has no envseal-mcp under mcp. ${hint}`, + }; + } + if (!isRecord(mcp)) { + return { + wired: false, + status: 'unreadable', + commandOk: null, + message: `.zed/settings.json mcp is not an object. ${hint}`, + }; + } + + const entry = mcp[ENVSEAL_MCP_SERVER_NAME]; + const kind = classifyEntry(entry); + if (kind === 'missing') { + return { + wired: false, + status: 'missing', + commandOk: null, + message: `.zed/settings.json has no envseal-mcp. ${hint}`, + }; + } + if (kind === 'stub') { + return { + wired: false, + status: 'stub', + commandOk: null, + message: `.zed/settings.json envseal-mcp is the empty stub. ${hint}`, + }; + } + + const rec = entry as Record; + const commandOk = options.probe === true ? probeVersion(rec) : null; + let message = 'Zed MCP is wired (project .zed/settings.json). [VERIFY: schema]'; + if (commandOk === false) { + message = + 'Zed MCP is configured, but the launch command did not report a version. Run `envseal init`. [VERIFY]'; + } + return { wired: true, status: 'wired', commandOk, message }; +} diff --git a/packages/cli/src/host.ts b/packages/cli/src/host.ts index 83a846e..5750d88 100644 --- a/packages/cli/src/host.ts +++ b/packages/cli/src/host.ts @@ -12,6 +12,26 @@ export interface HostInfo { recommendation: string; } +/** Host ids `init --host` accepts. `openhands` is Layer 1 only. */ +export const KNOWN_HOST_IDS = [ + 'claude-code', + 'cursor', + 'continue', + 'aider', + 'windsurf', + 'cline', + 'zed', + 'codex', + 'jetbrains', + 'goose', + 'copilot', + 'generic', + 'unknown', + 'openhands', +] as const; + +export type HostId = (typeof KNOWN_HOST_IDS)[number]; + /** * Detect the host environment from marker files and env vars. * Tier A: protocol + interception hooks (Claude Code) @@ -73,6 +93,110 @@ const TIER_B_ADVICE = const TIER_C_ADVICE = 'Tier C host with protocol only. No interception hooks available; prefer the keychain sink so .env holds only references.'; +const AIDER_CONF_PATTERNS = ['aider', '.aider']; + +export function aiderMarkerExists(root: string): boolean { + return AIDER_CONF_PATTERNS.some( + (pattern) => + existsSync(join(root, `${pattern}.conf.yml`)) || + existsSync(join(root, `${pattern}.conf.yaml`)) || + existsSync(join(root, `${pattern}.conf.json`)), + ); +} + +export function copilotSettingsExist(root: string): boolean { + const vscodeSettings = join(root, '.vscode', 'settings.json'); + try { + return existsSync(vscodeSettings) && /copilot/i.test(readFileSync(vscodeSettings, 'utf8')); + } catch { + return false; + } +} + +/** + * Every project-local host marker in this repo. Used by `init` so a dual-host + * tree (`.cursor/` + `.claude/`) gets both configs. Does not include AGENTS.md + * (Layer 1 is always applied) and does not scan `$HOME`. + */ +export function collectProjectHostIds(root: string): string[] { + const ids: string[] = []; + if (existsSync(join(root, '.claude'))) ids.push('claude-code'); + if (existsSync(join(root, '.cursor'))) ids.push('cursor'); + if (existsSync(join(root, '.continue'))) ids.push('continue'); + if (aiderMarkerExists(root)) ids.push('aider'); + if (existsSync(join(root, '.windsurf'))) ids.push('windsurf'); + if (existsSync(join(root, '.cline'))) ids.push('cline'); + if (existsSync(join(root, '.zed'))) ids.push('zed'); + if (existsSync(join(root, '.codex'))) ids.push('codex'); + if (existsSync(join(root, '.idea'))) ids.push('jetbrains'); + if (existsSync(join(root, 'goose.config.yaml')) || existsSync(join(root, '.goose'))) { + ids.push('goose'); + } + if (copilotSettingsExist(root)) ids.push('copilot'); + return ids; +} + +/** + * This-process host only. Used by `init` when the project has no markers. + * Never treats a global `~/.cursor` / `~/.codex` install as this project. + */ +export function detectProcessHostId(): string | undefined { + if (process.env.CLAUDECODE) return 'claude-code'; + if (process.env.CURSOR_WORKSPACE || process.env.CURSOR_VERSION) return 'cursor'; + if (process.env.CLINE_ROOT) return 'cline'; + if (process.env.ZED_EDITOR) return 'zed'; + if (process.env.CODEX_ROOT) return 'codex'; + if (process.env.GOOSE_ROOT) return 'goose'; + return undefined; +} + +export function parseHostOverride(raw: string): string[] | { error: string } { + const ids = raw + .split(',') + .map((s) => s.trim()) + .filter((s) => s.length > 0); + if (ids.length === 0) { + return { error: `unknown --host '${raw}'. Valid values: ${KNOWN_HOST_IDS.join(', ')}.` }; + } + const unknown = ids.filter((id) => !KNOWN_HOST_IDS.includes(id as HostId)); + if (unknown.length > 0) { + return { + error: `unknown --host '${unknown.join(', ')}'. Valid values: ${KNOWN_HOST_IDS.join(', ')}.`, + }; + } + return ids; +} + +/** + * Which hosts `init` should write Layer 2 config for. + * `--host` is an escape hatch (comma-separated ok). Never crawls `$HOME`. + */ +export function resolveInitHostIds( + root: string, + hostOverride?: string, +): { + ids: string[]; + source: 'flag' | 'project' | 'process' | 'none'; + error?: string; +} { + if (hostOverride !== undefined) { + const parsed = parseHostOverride(hostOverride); + if ('error' in parsed) { + return { ids: [], source: 'flag', error: parsed.error }; + } + return { ids: parsed, source: 'flag' }; + } + const project = collectProjectHostIds(root); + if (project.length > 0) { + return { ids: project, source: 'project' }; + } + const processId = detectProcessHostId(); + if (processId !== undefined) { + return { ids: [processId], source: 'process' }; + } + return { ids: [], source: 'none' }; +} + export function detectHost(root: string): HostInfo { /* ---------------- Pass 1: project-local evidence ---------------- */ @@ -125,14 +249,7 @@ export function detectHost(root: string): HostInfo { } // Tier C: Aider (project-local config forms). - const aiderConfPatterns = ['aider', '.aider']; - const aiderMarkerExists = aiderConfPatterns.some( - (pattern) => - existsSync(join(root, `${pattern}.conf.yml`)) || - existsSync(join(root, `${pattern}.conf.yaml`)) || - existsSync(join(root, `${pattern}.conf.json`)), - ); - if (aiderMarkerExists) { + if (aiderMarkerExists(root)) { return { id: 'aider', name: 'Aider', @@ -208,15 +325,7 @@ export function detectHost(root: string): HostInfo { // directory, so the honest marker is Copilot settings inside // .vscode/settings.json — a bare .vscode/ proves nothing, every VS Code // project has one. - const vscodeSettings = join(root, '.vscode', 'settings.json'); - let copilotSettings = false; - try { - copilotSettings = - existsSync(vscodeSettings) && /copilot/i.test(readFileSync(vscodeSettings, 'utf8')); - } catch { - // Unreadable settings are not evidence of Copilot. - } - if (copilotSettings) { + if (copilotSettingsExist(root)) { return { id: 'copilot', name: 'GitHub Copilot', @@ -238,7 +347,14 @@ export function detectHost(root: string): HostInfo { } /* ------------- Pass 2: environment / global-home evidence ------------- - * Reached ONLY when the project carries no marker of its own. */ + * Reached ONLY when the project carries no marker of its own. + * + * Process env (CLAUDECODE, CURSOR_*, …) names the host running *this* + * command. `$HOME` markers are labeling only — never a reason for `init` + * to write files. `~/.codex/` is intentionally not treated as Codex (see + * tests): a global install is not this project. `~/.codeium/windsurf`, + * `~/.cline`, `~/.config/zed` lump to Generic Agent, not a named host. + * `~/.continue/config.yaml` alone is Unknown, matching Continue docs. */ if (process.env.CLAUDECODE) { return { diff --git a/packages/cli/test/contract-e2e.test.ts b/packages/cli/test/contract-e2e.test.ts index f4a6c37..acc90ae 100644 --- a/packages/cli/test/contract-e2e.test.ts +++ b/packages/cli/test/contract-e2e.test.ts @@ -108,6 +108,13 @@ function writeManifest( ); } +function writeLayer1(root: string): void { + writeFileSync( + join(root, 'AGENTS.md'), + 'This repository uses envseal. Never read .env. Use envseal ensure and envseal run -- instead.\n', + ); +} + let tempDir: string; beforeEach(() => { @@ -570,6 +577,7 @@ describe('status and doctor: documented exit codes', () => { it('doctor exits 1 while a required key is missing and 0 once present', () => { writeManifest(tempDir, [{ key: 'DOCTOR_KEY' }]); + writeLayer1(tempDir); expect(runCli(tempDir, ['doctor', '--project', tempDir, '--json']).exitCode).toBe(1); writeFileSync(join(tempDir, '.env'), 'DOCTOR_KEY=value\n'); @@ -578,6 +586,7 @@ describe('status and doctor: documented exit codes', () => { it('doctor gitignore.covers uses ignore semantics, not substring match', () => { writeManifest(tempDir, [{ key: 'GITIGNORE_KEY' }]); + writeLayer1(tempDir); writeFileSync(join(tempDir, '.env'), 'GITIGNORE_KEY=value\n'); writeFileSync(join(tempDir, '.gitignore'), 'my.env.backup\n'); @@ -589,6 +598,7 @@ describe('status and doctor: documented exit codes', () => { it('doctor reports hookFailClosed from ENVSEAL_HOOK_FAIL_CLOSED', () => { writeManifest(tempDir, [{ key: 'HOOK_KEY' }]); + writeLayer1(tempDir); writeFileSync(join(tempDir, '.env'), 'HOOK_KEY=value\n'); const openDefault = runCli(tempDir, ['doctor', '--project', tempDir, '--json']); @@ -642,23 +652,36 @@ describe('init: --host validation and first-run guidance', () => { expect(r.exitCode, r.stdout).toBe(2); expect(r.stderr).toContain("unknown --host 'vscode'"); expect(r.stderr).toContain( - 'claude-code, cursor, continue, aider, windsurf, cline, zed, codex, jetbrains, goose, copilot, generic, unknown', + 'claude-code, cursor, continue, aider, windsurf, cline, zed, codex, jetbrains, goose, copilot, generic, unknown, openhands', ); // Rejected before any filesystem work: no manifest may appear. expect(existsSync(join(tempDir, 'env.schema.jsonc'))).toBe(false); }); - it('prints the MCP connection step for claude-code', () => { + it('prints the MCP connection step for claude-code and writes .mcp.json', () => { const r = runCli(tempDir, ['init', '--host', 'claude-code', '--project', tempDir]); expect(r.exitCode, r.stderr).toBe(0); expect(r.stdout).toContain('.mcp.json'); expect(r.stdout).toContain('envseal-mcp'); - expect(r.stdout).toContain('restart Claude Code'); + expect(r.stdout).toMatch(/restart Claude Code/i); + expect(r.stdout).not.toMatch(/protection tier A\b/i); + expect(existsSync(join(tempDir, '.mcp.json'))).toBe(true); + const mcp = JSON.parse(readFileSync(join(tempDir, '.mcp.json'), 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: string[] } }; + }; + expect(mcp.mcpServers['envseal-mcp'].args).toEqual(['-y', '@envseal/mcp-server']); + expect(['npx', 'npx.cmd']).toContain(mcp.mcpServers['envseal-mcp'].command); }); it('notes that an override may differ from what detection reports', () => { const r = runCli(tempDir, ['init', '--host', 'cursor', '--project', tempDir]); expect(r.exitCode, r.stderr).toBe(0); expect(r.stdout).toContain('Override recorded; envseal doctor reports what is actually detected.'); + expect(r.stdout).toContain('Reload MCP in Settings → MCP'); + const mcp = JSON.parse(readFileSync(join(tempDir, '.cursor', 'mcp.json'), 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: string[] } }; + }; + expect(mcp.mcpServers['envseal-mcp'].args).toEqual(['-y', '@envseal/mcp-server']); + expect(['npx', 'npx.cmd']).toContain(mcp.mcpServers['envseal-mcp'].command); }); }); diff --git a/packages/cli/test/cursor-wiring.test.ts b/packages/cli/test/cursor-wiring.test.ts new file mode 100644 index 0000000..a5c71bc --- /dev/null +++ b/packages/cli/test/cursor-wiring.test.ts @@ -0,0 +1,327 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { dirname, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { + cursorMcpLaunch, + cursorMcpSnippetJson, + inspectCursorMcp, + isEmptyEnvsealStub, + isStockNpxLaunch, + writeCursorHostFiles, +} from '../src/host-wiring/cursor.js'; +import { CURSOR_RULES_MDC } from '../src/host-wiring/cursor-rules.js'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(__dirname, '..', '..', '..'); +const binPath = join(__dirname, '..', 'dist', 'bin.js'); +const pluginMcp = join(repoRoot, 'plugins', 'cursor', 'mcp.json'); +const pluginRules = join(repoRoot, 'plugins', 'cursor', 'rules', 'envseal.mdc'); + +function fixture(): string { + return mkdtempSync(join(tmpdir(), 'envseal-cursor-wire-')); +} + +describe('cursor MCP launch snippet', () => { + it('uses npx on POSIX and npx.cmd on Windows, never --project', () => { + expect(cursorMcpLaunch('linux')).toEqual({ + command: 'npx', + args: ['-y', '@envseal/mcp-server'], + }); + expect(cursorMcpLaunch('darwin')).toEqual({ + command: 'npx', + args: ['-y', '@envseal/mcp-server'], + }); + expect(cursorMcpLaunch('win32')).toEqual({ + command: 'npx.cmd', + args: ['-y', '@envseal/mcp-server'], + }); + expect(JSON.stringify(cursorMcpLaunch('win32'))).not.toMatch(/--project/); + }); + + it('keeps plugins/cursor/mcp.json identical to the POSIX snippet', () => { + const shipped = JSON.parse(readFileSync(pluginMcp, 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: string[] } }; + }; + expect(shipped.mcpServers['envseal-mcp']).toEqual(cursorMcpLaunch('linux')); + }); + + it('keeps plugins/cursor/rules/envseal.mdc identical to the embedded copy', () => { + const normalize = (s: string) => s.replace(/\r\n/g, '\n').replace(/\s+$/u, ''); + expect(normalize(readFileSync(pluginRules, 'utf8'))).toBe(normalize(CURSOR_RULES_MDC)); + }); + + it('treats the old envseal-mcp PATH stub as replaceable', () => { + expect(isEmptyEnvsealStub({ command: 'envseal-mcp', args: [] })).toBe(true); + expect(isEmptyEnvsealStub({ command: 'envseal-mcp' })).toBe(true); + expect(isStockNpxLaunch({ command: 'npx', args: ['-y', '@envseal/mcp-server'] })).toBe(true); + expect( + isStockNpxLaunch({ + command: 'node', + args: ['/opt/envseal/packages/mcp-server/dist/bin.js'], + }), + ).toBe(false); + }); +}); + +describe('writeCursorHostFiles', () => { + let root: string; + let fakeHome: string; + + beforeEach(() => { + root = fixture(); + fakeHome = mkdtempSync(join(tmpdir(), 'envseal-cursor-home-')); + vi.stubEnv('HOME', fakeHome); + vi.stubEnv('USERPROFILE', fakeHome); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); + rmSync(fakeHome, { recursive: true, force: true }); + }); + + it('creates .cursor/mcp.json with the platform npx argv on a clean tree', () => { + const result = writeCursorHostFiles(root, process.platform); + expect(result.mcp).toBe('created'); + expect(result.rules).toBe('created'); + expect(result.reloadHint).toMatch(/Settings → MCP/); + + const parsed = JSON.parse(readFileSync(result.mcpPath, 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: string[] } }; + }; + expect(parsed.mcpServers['envseal-mcp']).toEqual(cursorMcpLaunch(process.platform)); + expect(readFileSync(result.rulesPath, 'utf8').replace(/\r\n/g, '\n').replace(/\s+$/u, '')).toBe( + CURSOR_RULES_MDC.replace(/\s+$/u, ''), + ); + expect(existsSync(join(fakeHome, '.cursor', 'mcp.json'))).toBe(false); + }); + + it('preserves sibling MCP servers and is idempotent', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync( + join(root, '.cursor', 'mcp.json'), + JSON.stringify( + { + mcpServers: { + github: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] }, + }, + }, + null, + 2, + ) + '\n', + ); + + const first = writeCursorHostFiles(root, 'linux'); + expect(first.mcp).toBe('merged'); + const afterFirst = JSON.parse(readFileSync(first.mcpPath, 'utf8')) as { + mcpServers: Record; + }; + expect(afterFirst.mcpServers.github).toEqual({ + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-github'], + }); + expect(afterFirst.mcpServers['envseal-mcp']).toEqual(cursorMcpLaunch('linux')); + + const second = writeCursorHostFiles(root, 'linux'); + expect(second.mcp).toBe('unchanged'); + expect(second.rules).toBe('unchanged'); + expect(JSON.parse(readFileSync(second.mcpPath, 'utf8'))).toEqual(afterFirst); + }); + + it('does not overwrite a hand-edited envseal-mcp entry', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + const custom = { + mcpServers: { + 'envseal-mcp': { + command: 'node', + args: ['/opt/custom/envseal-mcp.js'], + }, + other: { command: 'echo' }, + }, + }; + writeFileSync(join(root, '.cursor', 'mcp.json'), JSON.stringify(custom, null, 2) + '\n'); + + const result = writeCursorHostFiles(root, 'linux'); + expect(result.mcp).toBe('unchanged'); + expect(JSON.parse(readFileSync(result.mcpPath, 'utf8'))).toEqual(custom); + }); + + it('replaces the empty envseal-mcp stub but keeps siblings', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync( + join(root, '.cursor', 'mcp.json'), + JSON.stringify( + { + mcpServers: { + sibling: { command: 'keep-me' }, + 'envseal-mcp': { command: 'envseal-mcp', args: [] }, + }, + }, + null, + 2, + ) + '\n', + ); + + const result = writeCursorHostFiles(root, 'win32'); + expect(result.mcp).toBe('merged'); + const parsed = JSON.parse(readFileSync(result.mcpPath, 'utf8')) as { + mcpServers: Record; + }; + expect(parsed.mcpServers.sibling).toEqual({ command: 'keep-me' }); + expect(parsed.mcpServers['envseal-mcp']).toEqual(cursorMcpLaunch('win32')); + }); + + it('does not clobber an existing rules file', () => { + const rulesPath = join(root, '.cursor', 'rules', 'envseal.mdc'); + mkdirSync(join(root, '.cursor', 'rules'), { recursive: true }); + writeFileSync(rulesPath, 'user-edited\n', 'utf8'); + const result = writeCursorHostFiles(root, 'linux'); + expect(result.rules).toBe('unchanged'); + expect(readFileSync(rulesPath, 'utf8')).toBe('user-edited\n'); + }); + + it('skips an unreadable mcp.json instead of wiping it', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + const path = join(root, '.cursor', 'mcp.json'); + writeFileSync(path, '{ not json', 'utf8'); + const result = writeCursorHostFiles(root, 'linux'); + expect(result.mcp).toBe('skipped'); + expect(readFileSync(path, 'utf8')).toBe('{ not json'); + }); +}); + +describe('inspectCursorMcp', () => { + let root: string; + + beforeEach(() => { + root = fixture(); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('reports unwired MCP on a .cursor/ tree with empty mcpServers', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync(join(root, '.cursor', 'mcp.json'), JSON.stringify({ mcpServers: {} }) + '\n'); + const inspection = inspectCursorMcp(root, { probe: false, platform: 'linux' }); + expect(inspection.wired).toBe(false); + expect(inspection.status).toBe('missing'); + expect(inspection.message).toContain('envseal init'); + expect(inspection.message).not.toMatch(/plugins\//); + expect(inspection.message).toContain(cursorMcpSnippetJson('linux')); + }); + + it('reports the PATH stub as unwired', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync( + join(root, '.cursor', 'mcp.json'), + JSON.stringify({ mcpServers: { 'envseal-mcp': { command: 'envseal-mcp', args: [] } } }) + '\n', + ); + const inspection = inspectCursorMcp(root, { probe: false }); + expect(inspection.wired).toBe(false); + expect(inspection.status).toBe('stub'); + expect(inspection.message).toContain('envseal init'); + }); + + it('reports wired for the npx snippet without probing npx', () => { + writeCursorHostFiles(root, 'linux'); + const inspection = inspectCursorMcp(root, { probe: true, platform: 'linux' }); + expect(inspection.wired).toBe(true); + expect(inspection.status).toBe('wired'); + expect(inspection.commandOk).toBeNull(); + }); +}); + +describe('envseal init --host cursor (dist)', () => { + let root: string; + + beforeEach(() => { + root = fixture(); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('writes a schema-valid .cursor/mcp.json and does not touch $HOME', () => { + expect(existsSync(binPath), `binary missing at ${binPath}`).toBe(true); + const fakeHome = mkdtempSync(join(tmpdir(), 'envseal-cursor-init-home-')); + try { + const result = spawnSync('node', [binPath, 'init', '--host', 'cursor', '--project', root, '--json'], { + cwd: root, + encoding: 'utf8', + env: { ...process.env, HOME: fakeHome, USERPROFILE: fakeHome, CI: undefined }, + timeout: 20_000, + input: '', + }); + expect(result.status, result.stderr).toBe(0); + const parsed = JSON.parse(result.stdout) as { + host: string; + cursorWiring?: { mcp: string; rules: string }; + }; + expect(parsed.host).toBe('cursor'); + expect(parsed.cursorWiring?.mcp).toBe('created'); + expect(parsed.cursorWiring?.rules).toBe('created'); + + const mcp = JSON.parse(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: unknown } }; + }; + expect(mcp.mcpServers['envseal-mcp']).toEqual(cursorMcpLaunch(process.platform)); + expect(existsSync(join(fakeHome, '.cursor', 'mcp.json'))).toBe(false); + } finally { + rmSync(fakeHome, { recursive: true, force: true }); + } + }); +}); + +describe('envseal doctor Cursor MCP (dist)', () => { + let root: string; + + beforeEach(() => { + root = fixture(); + writeFileSync( + join(root, 'env.schema.jsonc'), + JSON.stringify({ version: 1, entries: [] }, null, 2) + '\n', + ); + mkdirSync(join(root, '.cursor'), { recursive: true }); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('exits 1 and names envseal init when mcpServers is empty', () => { + expect(existsSync(binPath), `binary missing at ${binPath}`).toBe(true); + writeFileSync(join(root, '.cursor', 'mcp.json'), JSON.stringify({ mcpServers: {} }) + '\n'); + const result = spawnSync('node', [binPath, 'doctor', '--json', '--project', root], { + cwd: root, + encoding: 'utf8', + timeout: 20_000, + input: '', + }); + expect(result.status, result.stderr).toBe(1); + const parsed = JSON.parse(result.stdout) as { + host: { id: string }; + agentWiring?: { mcp: string; instructions: string }; + mcp?: { wired: boolean; status: string; message: string }; + }; + expect(parsed.host.id).toBe('cursor'); + expect(parsed.agentWiring?.mcp).toBe('missing'); + expect(parsed.mcp?.wired).toBe(false); + expect(parsed.mcp?.status).toBe('missing'); + expect(parsed.mcp?.message).toContain('envseal init'); + expect(parsed.mcp?.message).not.toMatch(/plugins\//); + }); +}); diff --git a/packages/cli/test/host-wiring.test.ts b/packages/cli/test/host-wiring.test.ts new file mode 100644 index 0000000..ab3a06b --- /dev/null +++ b/packages/cli/test/host-wiring.test.ts @@ -0,0 +1,386 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { dirname, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { applyHostWiring } from '../src/host-wiring/apply.js'; +import { AGENTS_MD_CONTENT } from '../src/host-wiring/agents-md-content.js'; +import { AIDER_CONF_YML } from '../src/host-wiring/aider-conf.js'; +import { mcpLaunch } from '../src/host-wiring/mcp.js'; +import { mergeAgentsMd, hasEnvsealImperative } from '../src/host-wiring/agents-md.js'; +import { aiderReadListIncludesEnv } from '../src/host-wiring/aider.js'; +import { continueSnippetYaml } from '../src/host-wiring/continue.js'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(__dirname, '..', '..', '..'); +const binPath = join(__dirname, '..', 'dist', 'bin.js'); +const pluginAgents = join(repoRoot, 'plugins', 'generic', 'AGENTS.md'); +const pluginAider = join(repoRoot, 'plugins', 'aider', '.aider.conf.yml'); +const pluginContinue = join(repoRoot, 'plugins', 'continue', 'config.yaml'); + +function fixture(): string { + return mkdtempSync(join(tmpdir(), 'envseal-host-wire-')); +} + +function stripAgentEnv(fakeHome: string): Record { + const env: Record = {}; + for (const [k, v] of Object.entries(process.env)) { + if (v === undefined) continue; + if ( + k === 'CLAUDECODE' || + k === 'CURSOR_WORKSPACE' || + k === 'CURSOR_VERSION' || + k === 'CLINE_ROOT' || + k === 'ZED_EDITOR' || + k === 'CODEX_ROOT' || + k === 'GOOSE_ROOT' || + k === 'CI' + ) { + continue; + } + env[k] = v; + } + env.HOME = fakeHome; + env.USERPROFILE = fakeHome; + return env; +} + +function runInit( + root: string, + args: string[], + extraEnv: Record = {}, +): { status: number | null; stdout: string; stderr: string } { + const fakeHome = mkdtempSync(join(tmpdir(), 'envseal-init-home-')); + try { + const result = spawnSync('node', [binPath, 'init', '--project', root, '--json', ...args], { + cwd: root, + encoding: 'utf8', + env: { ...stripAgentEnv(fakeHome), ...extraEnv }, + timeout: 20_000, + input: '', + }); + return { + status: result.status, + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', + }; + } finally { + rmSync(fakeHome, { recursive: true, force: true }); + } +} + +function runDoctor(root: string): { status: number | null; stdout: string } { + const fakeHome = mkdtempSync(join(tmpdir(), 'envseal-doc-home-')); + try { + const result = spawnSync('node', [binPath, 'doctor', '--json', '--project', root], { + cwd: root, + encoding: 'utf8', + env: stripAgentEnv(fakeHome), + timeout: 20_000, + input: '', + }); + return { status: result.status, stdout: result.stdout ?? '' }; + } finally { + rmSync(fakeHome, { recursive: true, force: true }); + } +} + +const normalize = (s: string) => s.replace(/\r\n/g, '\n').replace(/\s+$/u, ''); + +describe('embedded plugin drift', () => { + it('keeps AGENTS.md identical to plugins/generic/AGENTS.md', () => { + expect(normalize(readFileSync(pluginAgents, 'utf8'))).toBe(normalize(AGENTS_MD_CONTENT)); + }); + + it('keeps aider conf identical to plugins/aider/.aider.conf.yml', () => { + expect(normalize(readFileSync(pluginAider, 'utf8'))).toBe(normalize(AIDER_CONF_YML)); + }); + + it('keeps Continue yaml using the POSIX npx snippet', () => { + const shipped = readFileSync(pluginContinue, 'utf8'); + expect(shipped).toContain('command: npx'); + expect(shipped).toContain('@envseal/mcp-server'); + expect(continueSnippetYaml('linux')).toContain('command: npx'); + expect(continueSnippetYaml('win32')).toContain('command: npx.cmd'); + }); +}); + +describe('applyHostWiring', () => { + let root: string; + let fakeHome: string; + + beforeEach(() => { + root = fixture(); + fakeHome = mkdtempSync(join(tmpdir(), 'envseal-wire-home-')); + vi.stubEnv('HOME', fakeHome); + vi.stubEnv('USERPROFILE', fakeHome); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); + rmSync(fakeHome, { recursive: true, force: true }); + }); + + it('always merges AGENTS.md without clobbering unrelated content', () => { + writeFileSync(join(root, 'AGENTS.md'), '# My project\n\nDo not delete me.\n', 'utf8'); + const result = applyHostWiring(root, [], 'linux'); + expect(result.agentsMd.action).toBe('merged'); + const text = readFileSync(join(root, 'AGENTS.md'), 'utf8'); + expect(text).toContain('Do not delete me.'); + expect(hasEnvsealImperative(text)).toBe(true); + const second = mergeAgentsMd(root); + expect(second.action).toBe('unchanged'); + }); + + it('writes Cursor MCP + rules on --host cursor (Windows npx.cmd)', () => { + const result = applyHostWiring(root, ['cursor'], 'win32'); + const mcp = JSON.parse(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')) as { + mcpServers: { 'envseal-mcp': { command: string; args: string[] } }; + }; + expect(mcp.mcpServers['envseal-mcp']).toEqual(mcpLaunch('win32')); + expect(existsSync(join(root, '.cursor', 'rules', 'envseal.mdc'))).toBe(true); + expect(existsSync(join(fakeHome, '.cursor', 'mcp.json'))).toBe(false); + expect(result.cursor?.mcp).toBe('created'); + }); + + it('writes both Cursor and Claude Code configs from dual markers', () => { + applyHostWiring(root, ['cursor', 'claude-code'], 'linux'); + const cursor = JSON.parse(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')); + const claude = JSON.parse(readFileSync(join(root, '.mcp.json'), 'utf8')); + expect(cursor.mcpServers['envseal-mcp']).toEqual(mcpLaunch('linux')); + expect(claude.mcpServers['envseal-mcp']).toEqual(mcpLaunch('linux')); + expect(existsSync(join(root, '.claude'))).toBe(true); + }); + + it('writes Windsurf, Cline, Zed, JetBrains project MCP files', () => { + applyHostWiring(root, ['windsurf', 'cline', 'zed', 'jetbrains'], 'linux'); + for (const rel of [ + '.windsurf/mcp_config.json', + '.cline/mcp_settings.json', + '.idea/mcp.json', + ]) { + const parsed = JSON.parse(readFileSync(join(root, rel), 'utf8')) as { + mcpServers: { 'envseal-mcp': unknown }; + }; + expect(parsed.mcpServers['envseal-mcp']).toEqual(mcpLaunch('linux')); + } + const zed = JSON.parse(readFileSync(join(root, '.zed', 'settings.json'), 'utf8')) as { + mcp: { 'envseal-mcp': unknown }; + other?: unknown; + }; + expect(zed.mcp['envseal-mcp']).toEqual(mcpLaunch('linux')); + }); + + it('merges Zed settings without clobbering sibling keys', () => { + mkdirSync(join(root, '.zed'), { recursive: true }); + writeFileSync( + join(root, '.zed', 'settings.json'), + JSON.stringify({ tab_size: 2, mcp: { other: { command: 'keep' } } }, null, 2) + '\n', + ); + applyHostWiring(root, ['zed'], 'linux'); + const zed = JSON.parse(readFileSync(join(root, '.zed', 'settings.json'), 'utf8')) as { + tab_size: number; + mcp: Record; + }; + expect(zed.tab_size).toBe(2); + expect(zed.mcp.other).toEqual({ command: 'keep' }); + expect(zed.mcp['envseal-mcp']).toEqual(mcpLaunch('linux')); + }); + + it('merges Copilot github.copilot.mcp into project settings.json', () => { + applyHostWiring(root, ['copilot'], 'linux'); + const settings = JSON.parse(readFileSync(join(root, '.vscode', 'settings.json'), 'utf8')) as { + 'github.copilot.mcp': Array<{ name: string; command: string; args: string[] }>; + }; + expect(settings['github.copilot.mcp'][0]).toEqual({ + name: 'envseal-mcp', + ...mcpLaunch('linux'), + }); + }); + + it('merges Aider conf so .env is not on read', () => { + writeFileSync( + join(root, '.aider.conf.yml'), + 'read:\n - .env\n - README.md\n', + 'utf8', + ); + applyHostWiring(root, ['aider'], 'linux'); + const text = readFileSync(join(root, '.aider.conf.yml'), 'utf8'); + expect(aiderReadListIncludesEnv(text)).toBe(false); + expect(text).toContain('README.md'); + expect(text).toContain('env.schema.jsonc'); + }); + + it('does not invent IDE files for generic/unknown', () => { + applyHostWiring(root, ['generic'], 'linux'); + expect(existsSync(join(root, '.cursor'))).toBe(false); + expect(existsSync(join(root, 'AGENTS.md'))).toBe(true); + expect(existsSync(join(fakeHome, '.cursor'))).toBe(false); + }); +}); + +describe('envseal init (dist)', () => { + let root: string; + + beforeEach(() => { + root = fixture(); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('init --host cursor writes mcp + rules and AGENTS.md', () => { + expect(existsSync(binPath), `binary missing at ${binPath}`).toBe(true); + const r = runInit(root, ['--host', 'cursor']); + expect(r.status, r.stderr).toBe(0); + const parsed = JSON.parse(r.stdout) as { + host: string; + protectionTier: string; + cursorWiring?: { mcp: string; rules: string }; + agentsMd?: { action: string }; + }; + expect(parsed.cursorWiring?.mcp).toBe('created'); + expect(parsed.cursorWiring?.rules).toBe('created'); + expect(parsed.agentsMd?.action).toBe('created'); + expect(parsed.protectionTier).not.toBe('C'); + expect(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')).toContain('@envseal/mcp-server'); + expect(existsSync(join(root, 'AGENTS.md'))).toBe(true); + }); + + it('init with no --host on a .cursor/ tree matches --host cursor', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + const r = runInit(root, []); + expect(r.status, r.stderr).toBe(0); + expect(existsSync(join(root, '.cursor', 'mcp.json'))).toBe(true); + expect(existsSync(join(root, '.cursor', 'rules', 'envseal.mdc'))).toBe(true); + }); + + it('writes both MCP configs when .cursor/ and .claude/ exist', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + mkdirSync(join(root, '.claude'), { recursive: true }); + const r = runInit(root, []); + expect(r.status, r.stderr).toBe(0); + expect(existsSync(join(root, '.cursor', 'mcp.json'))).toBe(true); + expect(existsSync(join(root, '.mcp.json'))).toBe(true); + const parsed = JSON.parse(r.stdout) as { wiredHosts: string[] }; + expect(parsed.wiredHosts).toEqual(expect.arrayContaining(['cursor', 'claude-code'])); + }); + + it('bare tree with no process host writes AGENTS.md only', () => { + const r = runInit(root, []); + expect(r.status, r.stderr).toBe(0); + expect(existsSync(join(root, 'AGENTS.md'))).toBe(true); + expect(existsSync(join(root, '.cursor'))).toBe(false); + expect(existsSync(join(root, '.mcp.json'))).toBe(false); + const parsed = JSON.parse(r.stdout) as { wiringSource: string; wiredHosts: string[] }; + expect(parsed.wiringSource).toBe('none'); + expect(parsed.wiredHosts).toEqual([]); + }); + + it('init --host claude-code writes .mcp.json and does not claim Tier A', () => { + const r = runInit(root, ['--host', 'claude-code']); + expect(r.status, r.stderr).toBe(0); + const parsed = JSON.parse(r.stdout) as { host: string; protectionTier: string }; + expect(existsSync(join(root, '.mcp.json'))).toBe(true); + expect(parsed.protectionTier).toBe('B'); + expect(r.stdout).not.toMatch(/"protectionTier":\s*"A"/); + }); + + it('init --host aider keeps .env off the read list', () => { + const r = runInit(root, ['--host', 'aider']); + expect(r.status, r.stderr).toBe(0); + const text = readFileSync(join(root, '.aider.conf.yml'), 'utf8'); + expect(aiderReadListIncludesEnv(text)).toBe(false); + }); + + it('second init is idempotent and keeps sibling MCP servers', () => { + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync( + join(root, '.cursor', 'mcp.json'), + JSON.stringify({ + mcpServers: { + github: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] }, + }, + }) + '\n', + ); + expect(runInit(root, []).status).toBe(0); + const afterFirst = JSON.parse(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')); + expect(afterFirst.mcpServers.github.command).toBe('npx'); + expect(runInit(root, []).status).toBe(0); + const afterSecond = JSON.parse(readFileSync(join(root, '.cursor', 'mcp.json'), 'utf8')); + expect(afterSecond).toEqual(afterFirst); + }); +}); + +describe('envseal doctor wiring (dist)', () => { + let root: string; + + beforeEach(() => { + root = fixture(); + writeFileSync( + join(root, 'env.schema.jsonc'), + JSON.stringify({ version: 1, entries: [] }, null, 2) + '\n', + ); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('fails on empty .cursor/mcp.json (folder is not wiring)', () => { + expect(existsSync(binPath), `binary missing at ${binPath}`).toBe(true); + mkdirSync(join(root, '.cursor'), { recursive: true }); + writeFileSync(join(root, '.cursor', 'mcp.json'), JSON.stringify({ mcpServers: {} }) + '\n'); + const r = runDoctor(root); + expect(r.status).toBe(1); + const parsed = JSON.parse(r.stdout) as { + host: { id: string }; + agentWiring: { mcp: string; instructions: string }; + mcp?: { wired: boolean; status: string }; + }; + expect(parsed.host.id).toBe('cursor'); + expect(parsed.agentWiring.mcp).toBe('missing'); + expect(parsed.mcp?.wired).toBe(false); + }); + + it('passes after init --host cursor', () => { + const init = runInit(root, ['--host', 'cursor']); + expect(init.status, init.stderr).toBe(0); + const r = runDoctor(root); + expect(r.status, r.stdout).toBe(0); + const parsed = JSON.parse(r.stdout) as { + agentWiring: { mcp: string; instructions: string }; + mcp?: { wired: boolean }; + }; + expect(parsed.agentWiring.mcp).toBe('ok'); + expect(parsed.agentWiring.instructions).toBe('ok'); + expect(parsed.mcp?.wired).toBe(true); + }); + + it('Continue after init is labeled but MCP is not OOTB', () => { + const init = runInit(root, ['--host', 'continue']); + expect(init.status, init.stderr).toBe(0); + const r = runDoctor(root); + expect(r.status).toBe(1); + const parsed = JSON.parse(r.stdout) as { + host: { id: string }; + agentWiring: { mcp: string; instructions: string }; + mcp?: { message: string }; + }; + expect(parsed.host.id).toBe('continue'); + expect(parsed.agentWiring.mcp).toBe('missing'); + expect(parsed.agentWiring.instructions).toBe('ok'); + expect(parsed.mcp?.message).toMatch(/not OOTB/i); + }); +}); diff --git a/packages/cli/test/host.test.ts b/packages/cli/test/host.test.ts index c567ff1..a4541d9 100644 --- a/packages/cli/test/host.test.ts +++ b/packages/cli/test/host.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { detectHost } from '../src/host.js'; +import { detectHost, collectProjectHostIds, resolveInitHostIds } from '../src/host.js'; describe('host detection', () => { let tempDir: string; @@ -248,6 +248,20 @@ describe('host detection', () => { expect(host.reason).toMatch(/no project markers/i); }); + it('$HOME-only Windsurf/Zed label as Generic Agent, not a named host', () => { + mkdirSync(join(tempDir, '.codeium', 'windsurf'), { recursive: true }); + const windsurfProj = join(tempDir, 'ws-proj'); + mkdirSync(windsurfProj, { recursive: true }); + expect(detectHost(windsurfProj).id).toBe('generic'); + + rmSync(join(tempDir, '.codeium'), { recursive: true, force: true }); + mkdirSync(join(tempDir, '.config', 'zed'), { recursive: true }); + const zedProj = join(tempDir, 'zed-proj'); + mkdirSync(zedProj, { recursive: true }); + expect(detectHost(zedProj).id).toBe('generic'); + expect(detectHost(zedProj).name).toBe('Generic Agent'); + }); + it('CLAUDECODE env signal yields tier B, and loses to a project .cursor/', () => { vi.stubEnv('CLAUDECODE', '1'); mkdirSync(join(tempDir, '.cursor'), { recursive: true }); @@ -300,3 +314,58 @@ describe('host detection', () => { expect(host.recommendation.length).toBeGreaterThan(0); }); }); + +describe('collectProjectHostIds / resolveInitHostIds', () => { + let tempDir: string; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), 'envseal-test-hosts-')); + vi.stubEnv('USERPROFILE', tempDir); + vi.stubEnv('HOME', tempDir); + vi.stubEnv('CLAUDECODE', undefined); + vi.stubEnv('CURSOR_WORKSPACE', undefined); + vi.stubEnv('CURSOR_VERSION', undefined); + vi.stubEnv('CLINE_ROOT', undefined); + vi.stubEnv('ZED_EDITOR', undefined); + vi.stubEnv('CODEX_ROOT', undefined); + vi.stubEnv('GOOSE_ROOT', undefined); + }); + + afterEach(() => { + try { + rmSync(tempDir, { recursive: true }); + } catch { + /* ignore */ + } + vi.unstubAllEnvs(); + }); + + it('collects every project marker, not first-wins', () => { + mkdirSync(join(tempDir, '.claude'), { recursive: true }); + mkdirSync(join(tempDir, '.cursor'), { recursive: true }); + const ids = collectProjectHostIds(tempDir); + expect(ids).toEqual(expect.arrayContaining(['claude-code', 'cursor'])); + expect(ids).toHaveLength(2); + // detectHost remains first-wins for doctor's primary line + expect(detectHost(tempDir).id).toBe('claude-code'); + }); + + it('does not treat AGENTS.md as a host to wire', () => { + writeFileSync(join(tempDir, 'AGENTS.md'), 'hello'); + expect(collectProjectHostIds(tempDir)).toEqual([]); + expect(resolveInitHostIds(tempDir).source).toBe('none'); + }); + + it('uses this process only when the tree has no project markers', () => { + vi.stubEnv('CURSOR_VERSION', '1.0.0'); + const resolved = resolveInitHostIds(tempDir); + expect(resolved).toEqual({ ids: ['cursor'], source: 'process' }); + }); + + it('ignores $HOME installs when resolving init hosts', () => { + mkdirSync(join(tempDir, '.cursor'), { recursive: true }); // fake home + const proj = join(tempDir, 'proj'); + mkdirSync(proj, { recursive: true }); + expect(resolveInitHostIds(proj).source).toBe('none'); + }); +}); diff --git a/packages/core/package.json b/packages/core/package.json index 63075ec..2416dbe 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/core", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/detector/package.json b/packages/detector/package.json index fc9a79f..d2c4090 100644 --- a/packages/detector/package.json +++ b/packages/detector/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/detector", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/http-server/package.json b/packages/http-server/package.json index e40806e..9fcaae6 100644 --- a/packages/http-server/package.json +++ b/packages/http-server/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/http-server", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index f73fe1c..75ea13a 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/mcp-server", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/mcp-server/src/cli-args.ts b/packages/mcp-server/src/cli-args.ts index 251c0c5..9ebee33 100644 --- a/packages/mcp-server/src/cli-args.ts +++ b/packages/mcp-server/src/cli-args.ts @@ -7,7 +7,7 @@ import { findProjectRoot } from '@envseal/core'; * be tested without importing a module whose side effect is starting a server. */ -export const VERSION = '0.1.4'; +export const VERSION = '0.1.5'; export const USAGE = `envseal-mcp ${VERSION} diff --git a/packages/prompters/package.json b/packages/prompters/package.json index f794de3..c5d4877 100644 --- a/packages/prompters/package.json +++ b/packages/prompters/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/prompters", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index bbf638e..c59602b 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/protocol", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/registry/package.json b/packages/registry/package.json index 0b2fdcc..864835a 100644 --- a/packages/registry/package.json +++ b/packages/registry/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/registry", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index c1c5049..1d06866 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@envseal/sdk", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "license": "Apache-2.0", "main": "./dist/index.js", diff --git a/plugins/aider/README.md b/plugins/aider/README.md index 4d5f98c..71a1bf3 100644 --- a/plugins/aider/README.md +++ b/plugins/aider/README.md @@ -18,18 +18,22 @@ catastrophic. The config and recipe below are written around that fact. ## Install -1. Copy `.aider.conf.yml` to your project root (or merge the `read` list into - your existing config). +```sh +npm install -D @envseal/cli +npx envseal init --host aider +``` -2. Make sure `envseal` is on your `PATH` (`npm i -g @envseal/cli`). +`init` merges Layer 1 `AGENTS.md` and this `.aider.conf.yml` so `.env` is not +on `read:`. Re-running is idempotent and will strip `.env` from an existing +`read` list. -3. In an Aider session, use the `/run` command: +In an Aider session, use the `/run` command: - ``` - /run envseal ensure - /run envseal run -- pytest - /run envseal doctor - ``` +``` +/run envseal ensure +/run envseal run -- pytest +/run envseal doctor +``` ## Shell recipe (for hooks, scripts, CI) @@ -64,4 +68,4 @@ Tier C has no guardrails at all. Use the `keychain` sink so `.env` holds only a References are resolved by `envseal run -- `. Tools that read `.env` directly cannot resolve references; on Aider, prefer the `keychain` sink unless -you specifically need a plaintext `.env` for other tooling. \ No newline at end of file +you specifically need a plaintext `.env` for other tooling. diff --git a/plugins/continue/README.md b/plugins/continue/README.md index 2f4bc2e..1d341eb 100644 --- a/plugins/continue/README.md +++ b/plugins/continue/README.md @@ -4,24 +4,43 @@ |---|---| | **Binding tier** | 1 — MCP over stdio | | **Protection tier** | **B** — protocol + advisory config only | -| **Files** | `config.yaml` | +| **Files** | `config.yaml` (project snippet; global merge is manual) | Continue is a **Tier B** host: it speaks MCP (binding tier 1) but has no interception hooks, so a shell command that leaks a value still reaches the transcript. The config registers the broker; it does not police anything. +MCP is **not OOTB** from `init` because Continue loads `~/.continue/config.yaml` +and envseal does not write `$HOME`. ## Install -1. **MCP server.** Merge the `mcpServers` block from `config.yaml` into - `~/.continue/config.yaml` (or `config.json` for the JSON config). +```sh +npm install -D @envseal/cli +npx envseal init --host continue +``` + +1. **Layer 1.** `init` merges `AGENTS.md` so the agent can run `envseal ensure` + / `envseal run --` without MCP. + +2. **MCP (manual).** Merge the `mcpServers` block from `config.yaml` into + `~/.continue/config.yaml`. `init` also writes a project `.continue/config.yaml` + (detection marker + the same snippet). POSIX: + + ```yaml + mcpServers: + - name: envseal-mcp + command: npx + args: ["-y", "@envseal/mcp-server"] + ``` - The `envseal-mcp` command must be on your `PATH` (it ships with - `@envseal/mcp-server`, a dependency of `@envseal/cli`). In a monorepo checkout - substitute `"command": "node"` + `"args": ["/packages/mcp-server/dist/bin.js"]`. + On Windows use `npx.cmd`. Do not copy this into `$HOME` via envseal; merge + it yourself. `[VERIFY]` HUB schema vs `experimental.mcpServers`. -2. **Restart** Continue so it re-reads the config and connects to the server. +3. **Restart** Continue so it re-reads the global config. -3. **Verify.** Run `envseal doctor` — it should report `Host: Continue (Tier B)`. +4. **Verify.** `envseal doctor` reports `Host: Continue (Tier B)` from project + `.continue/`. `agentWiring.mcp` stays `missing` until the global merge + (not OOTB). ## Keychain recommendation (Tier B) @@ -42,4 +61,4 @@ sink so `.env` holds only a `secret-ref://envseal/...` reference: The value never touches disk in plaintext and is resolved by `envseal run -- ` at launch. Tools that read `.env` directly (Docker Compose, Next.js, Vite) cannot resolve references — weigh that against the leak risk of -Tier B. \ No newline at end of file +Tier B. diff --git a/plugins/continue/config.yaml b/plugins/continue/config.yaml index feeb369..ea6e9f8 100644 --- a/plugins/continue/config.yaml +++ b/plugins/continue/config.yaml @@ -1,4 +1,9 @@ -# ~/.continue/config.yaml — envseal MCP server (Continue — Tier B host) +# Project-local copy of the envseal MCP snippet (Continue — Tier B host) +# +# Continue currently loads MCP from ~/.continue/config.yaml. `envseal init` +# writes this file under project `.continue/` so doctor can detect the host +# and so you have a block to merge into the global config. envseal never +# writes $HOME. # # [VERIFY: recent Continue versions moved toward the new HUB config.yaml # schema; if your build does not accept a top-level `mcpServers` list, use @@ -10,5 +15,5 @@ mcpServers: - name: envseal-mcp - command: envseal-mcp - args: [] \ No newline at end of file + command: npx + args: ["-y", "@envseal/mcp-server"] diff --git a/plugins/cursor/README.md b/plugins/cursor/README.md index 31d9a56..8fd61b0 100644 --- a/plugins/cursor/README.md +++ b/plugins/cursor/README.md @@ -12,30 +12,42 @@ advisory — it reduces accidents, it cannot block them. ## Install -1. **MCP server.** Copy `mcp.json` to `.cursor/mcp.json` at your project root for - a project-scoped server, or to `~/.cursor/mcp.json` for every project: - - ```sh - cp plugins/cursor/mcp.json .cursor/mcp.json - ``` - - The `envseal-mcp` command must be on your `PATH` (it ships with `@envseal/mcp-server`, - which is installed as a dependency of `@envseal/cli`). If you run from a monorepo - checkout, point `command` at `packages/mcp-server/dist/bin.js` and add - `"args": ["--project", ""]` if the workspace root is not the MCP cwd. +```sh +npm install -D @envseal/cli +npx envseal init +# or: npx envseal init --host cursor +``` -2. **Restart the MCP servers** (Cursor: `Settings → MCP` shows the connection status). +That is the primary path. `init` writes project-scoped `.cursor/mcp.json` and +`.cursor/rules/envseal.mdc`. Do not copy these files by hand, and do not put +envseal in `~/.cursor/mcp.json` — Cursor launches that process with `cwd` = +your home directory, which is not a project. -3. **Rules.** Copy `rules/envseal.mdc` into `.cursor/rules/` (or `~/.cursor/rules/` - to apply globally): +1. **MCP server.** `envseal init` merges this snippet (POSIX shown; Windows + gets `"command": "npx.cmd"`). Cursor does not use `node_modules/.bin`, so + `npx -y @envseal/mcp-server` is the launch that works without a global + install. `--project` is not written: project MCP already has the workspace + as cwd. - ```sh - mkdir -p .cursor/rules && cp plugins/cursor/rules/envseal.mdc .cursor/rules/ + ```json + { + "mcpServers": { + "envseal-mcp": { + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] + } + } + } ``` -4. **Sink.** Because Cursor is Tier B, set the `keychain` sink (see below). +`init` always merges Layer 1 `AGENTS.md`. Reload MCP (`Settings → MCP` shows the +connection status). `envseal doctor` reports `Host: Cursor (Tier B)` and fails if +`envseal-mcp` is missing from `.cursor/mcp.json`. Re-run `envseal init` to merge +it. -5. **Verify.** Run `envseal doctor` — it should report `Host: Cursor (Tier B)`. +From a monorepo checkout you can point `command` at +`node` + `packages/mcp-server/dist/bin.js` instead of npx; `init` will not +overwrite that customization. ## Keychain recommendation (Tier B) @@ -57,4 +69,4 @@ touches disk in plaintext: References are resolved when a command runs via `envseal run -- `. Note: tools that read `.env` directly (Docker Compose, Next.js, Vite) cannot resolve references — for those, weigh the leak risk of Tier B against the convenience of the -`dotenv` sink. \ No newline at end of file +`dotenv` sink. diff --git a/plugins/cursor/mcp.json b/plugins/cursor/mcp.json index 8353eec..4462844 100644 --- a/plugins/cursor/mcp.json +++ b/plugins/cursor/mcp.json @@ -1,8 +1,8 @@ { "mcpServers": { "envseal-mcp": { - "command": "envseal-mcp", - "args": [] + "command": "npx", + "args": ["-y", "@envseal/mcp-server"] } } -} \ No newline at end of file +} diff --git a/plugins/cursor/rules/envseal.mdc b/plugins/cursor/rules/envseal.mdc index 4835a06..3e55f13 100644 --- a/plugins/cursor/rules/envseal.mdc +++ b/plugins/cursor/rules/envseal.mdc @@ -13,12 +13,10 @@ Cursor rules are advisory, not enforced. Treat these as hard rules regardless. Instead, use the envseal broker via MCP: - `env_describe` — read-only status of the declared keys (present, format-valid, last verified). It never returns values and there is no way to make it do so. -- `env_describe` — read-only status of the declared keys (present, format-valid, last verified). It never returns values and there is no way to make it do so. +- `env_request` — collect the missing keys from the user through a secure prompt. It returns a ticket, never a value; follow up with `env_await`. - `env_declare` — declare a key this project needs, with format and provider metadata. -- `env_request` — collect the missing keys from the user through a secure prompt. It returns a ticket, never a value. -- `env_await` — poll that ticket until the user finishes. Outcomes only (stored, cancelled, invalid_format); never a value. - `env_verify` — test that a key actually works (classified result only). - `env_use` — run a command with secrets injected into the child process; output is redacted. -- `env_revoke` — remove a key after user confirmation and get the rotation URL. +- `env_revoke` — remove a key and get the rotation URL. If a required key is missing, `env_request` it. Never read `.env` to find it, and never print it back. \ No newline at end of file diff --git a/plugins/generic/README.md b/plugins/generic/README.md index 52d1c10..c877373 100644 --- a/plugins/generic/README.md +++ b/plugins/generic/README.md @@ -13,8 +13,8 @@ ever printed. These two files are the generic drop-in: -- **`AGENTS.md`** — paste into your project's `AGENTS.md` (or `CLAUDE.md`, - `CONTRIBUTING.md`, or wherever your agent reads instructions). It tells any +- **`AGENTS.md`** — `npx envseal init` merges this into your project's + `AGENTS.md` (create or append; never clobbers unrelated content). It tells any agent, in imperative form, to never read `.env`, never echo variables, and to use `envseal ensure` / `envseal run --` instead. - **`pre-commit`** — a dependency-free POSIX `sh` git hook (only `git`, `grep`, @@ -24,7 +24,15 @@ These two files are the generic drop-in: ## Install ```sh -cp plugins/generic/AGENTS.md AGENTS.md # or merge the contents +npm install -D @envseal/cli +npx envseal init +# Layer 1 only on a bare tree; or: +npx envseal init --host generic +``` + +Optional pre-commit hook: + +```sh install -m 0755 plugins/generic/pre-commit .git/hooks/pre-commit ``` @@ -35,7 +43,7 @@ envseal ensure # prompt for every missing required key envseal status --json # machine-readable presence metadata envseal run -- # run with secrets injected, output redacted envseal verify --json # classified verification results -envseal doctor --json # host tier, gitignore, permissions, missing keys +envseal doctor --json # host tier, agentWiring, gitignore, missing keys ``` `AGENTS.md` is an advisory guardrail: an agent that ignores instructions can @@ -60,4 +68,4 @@ With no interception hooks, prefer the `keychain` sink so `.env` holds only a References are resolved by `envseal run -- `. Tools that read `.env` directly cannot resolve them; on a generic host with only advisory guardrails, -the leak risk almost always outweighs that convenience. \ No newline at end of file +the leak risk almost always outweighs that convenience. diff --git a/test/host-matrix.test.ts b/test/host-matrix.test.ts index 7302838..f258321 100644 --- a/test/host-matrix.test.ts +++ b/test/host-matrix.test.ts @@ -124,7 +124,11 @@ const PROJECT_HOSTS: Array<{ mkdirSync(join(root, '.vscode')); writeFileSync( join(root, '.vscode', 'settings.json'), - JSON.stringify({ 'github.copilot.mcp': [{ name: 'envseal-mcp', command: 'envseal-mcp' }] }), + JSON.stringify({ + 'github.copilot.mcp': [ + { name: 'envseal-mcp', command: 'npx', args: ['-y', '@envseal/mcp-server'] }, + ], + }), ); }, }, @@ -186,6 +190,16 @@ function extractMcpCommand(config: unknown): { command: string; args: unknown } return null; } +/** Project MCP launch: npx -y @envseal/mcp-server (npx.cmd on Windows), or the Claude plugin CJS. */ +function isShippedMcpLaunch(launch: { command: string; args: unknown }): boolean { + const cmd = launch.command.replace(/\.cmd$/i, ''); + if (cmd === 'npx') { + const args = Array.isArray(launch.args) ? launch.args.map(String) : []; + return args.includes('-y') && args.includes('@envseal/mcp-server'); + } + return launch.command === 'node' && JSON.stringify(launch.args).includes('envseal-mcp'); +} + interface JsonRpcResponse { id?: number; result?: { tools?: Array<{ name: string }> }; @@ -321,11 +335,13 @@ describe('documented hosts have pages and detection', () => { }); describe('shipped plugin configs', () => { - it('Cursor mcp.json launches envseal-mcp over stdio', () => { + it('Cursor mcp.json launches envseal-mcp over stdio via npx', () => { const cfg = JSON.parse(readFileSync(join(ROOT, 'plugins', 'cursor', 'mcp.json'), 'utf8')) as unknown; const launch = extractMcpCommand(cfg); - expect(launch?.command).toBe('envseal-mcp'); - expect(launch?.args).toEqual([]); + expect(launch).not.toBeNull(); + expect(isShippedMcpLaunch(launch!)).toBe(true); + expect(launch?.command).toBe('npx'); + expect(launch?.args).toEqual(['-y', '@envseal/mcp-server']); }); it('Claude plugin .mcp.json points at the bundled CJS (exists after plugin build)', () => { @@ -343,7 +359,8 @@ describe('shipped plugin configs', () => { it('Continue config registers envseal-mcp', () => { const yaml = readFileSync(join(ROOT, 'plugins', 'continue', 'config.yaml'), 'utf8'); expect(yaml).toMatch(/name:\s*envseal-mcp/); - expect(yaml).toMatch(/command:\s*envseal-mcp/); + expect(yaml).toMatch(/command:\s*npx/); + expect(yaml).toMatch(/@envseal\/mcp-server/); }); it('Aider read-list never includes .env', () => { @@ -373,7 +390,7 @@ describe('shipped plugin configs', () => { }); describe('install snippets in docs/hosts', () => { - it('every JSON MCP snippet launches envseal-mcp (or node + bundled bin)', () => { + it('every JSON MCP snippet launches via npx @envseal/mcp-server (or node + bundled bin)', () => { const offenders: string[] = []; for (const file of readdirSync(HOST_DOCS)) { if (!file.endsWith('.md') || file === 'README.md') continue; @@ -389,22 +406,22 @@ describe('install snippets in docs/hosts', () => { } const launch = extractMcpCommand(parsed); if (launch === null) continue; - const ok = - launch.command === 'envseal-mcp' || - (launch.command === 'node' && JSON.stringify(launch.args).includes('envseal-mcp')); - if (!ok) offenders.push(`${file}: command=${launch.command}`); + if (!isShippedMcpLaunch(launch)) offenders.push(`${file}: command=${launch.command}`); } } expect(offenders).toEqual([]); }); - it('toml/yaml host snippets name envseal-mcp', () => { + it('toml/yaml host snippets launch via npx @envseal/mcp-server', () => { const codex = readFileSync(join(HOST_DOCS, 'codex.md'), 'utf8'); - expect(codex).toMatch(/command\s*=\s*"envseal-mcp"/); + expect(codex).toMatch(/command\s*=\s*"npx"/); + expect(codex).toMatch(/@envseal\/mcp-server/); const goose = readFileSync(join(HOST_DOCS, 'goose.md'), 'utf8'); - expect(goose).toMatch(/cmd:\s*envseal-mcp/); + expect(goose).toMatch(/cmd:\s*npx/); + expect(goose).toMatch(/@envseal\/mcp-server/); const cont = readFileSync(join(HOST_DOCS, 'continue.md'), 'utf8'); - expect(cont).toMatch(/command:\s*envseal-mcp/); + expect(cont).toMatch(/command:\s*npx/); + expect(cont).toMatch(/@envseal\/mcp-server/); }); });