A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(security): keep connector state in memory, block credential reads, show full approvals, and disable subagents until stage 2
Alan Buscaglia8651bba4c8cd
diff --git a/README.md b/README.mdindex c153f7e..292a37c 100644--- a/README.md+++ b/README.md@@ -39,7 +39,7 @@ The assistant keeps to its own instance. The agent works in `~/.gentle-dot/worksMemory uses your global Engram (`~/.engram`, server on port 7437, or your own `ENGRAM_DATA_DIR`, `ENGRAM_PORT`, and `ENGRAM_URL`), and everything the assistant remembers goes to the project `gentle-dot`. If Engram is not running, the assistant starts it with your data folder. `GENTLE_DOT_ENGRAM_DATA_DIR` points at another data folder; `GENTLE_DOT_ENGRAM=private` gives the assistant a memory of its own instead (port 7438, `GENTLE_DOT_ENGRAM_PORT`). Memories saved by earlier versions in `~/.gentle-dot/home/.engram` are not moved to the global Engram.-Connectors let the assistant use Notion, Linear, and Atlassian through their official MCP servers: open Connectors (the plug icon, or type `/connectors`), choose Connect, and approve access in the browser. Each connector is "Read only" (it can search and read) or "Read and send"; even then, the assistant asks you with a preview before every action that sends or changes something. The daemon alone writes the engine's `mcp.json` (`~/.gentle-dot/agent`) from `~/.gentle-dot/connectors.json` and puts it back if anything else changed it.+Connectors let the assistant use Notion, Linear, and Atlassian through their official MCP servers: open Connectors (the plug icon, or type `/connectors`), choose Connect, and approve access in the browser. Each connector is "Read only" (it can search and read) or "Read and send"; even then, the assistant asks you with a preview before every action that sends or changes something. The daemon reads `~/.gentle-dot/connectors.json` once when it starts and keeps your choices in memory; it alone writes that file and the engine's `mcp.json` (`~/.gentle-dot/agent`), and if anything else changes them while it runs, it puts them back and tells you "A change to your connectors was blocked." The assistant cannot read your sign-ins and keys with its file tools; its shell commands are checked too, but that check is best effort, not a security boundary.## Checksdiff --git a/docs/design.md b/docs/design.mdindex 0094456..0e267bd 100644--- a/docs/design.md+++ b/docs/design.md@@ -9,7 +9,7 @@ Status: design for local development. The VPS deployment is documented, not perfGoals:- One assistant, always on, reachable from the desktop (floating Dot, menu bar, global shortcut) and from a web page.-- The agent behaves exactly like Gentle Shell: same tools, ODD workflow, subagents, skills, and Engram memory.+- The agent behaves exactly like Gentle Shell: same tools, ODD workflow, skills, and Engram memory. Subagents are off until S25 (their child engines do not load the connector approval guard; §4, Connectors).- The user never sees Gentle Shell: no Gentle branding, commands, or terminal in the product surface.- Everything runs locally first; the same daemon can later run on a VPS (HostGator) with Docker.@@ -62,9 +62,9 @@ docs/ design, deployment guide, security checklist## 3. Agent supervisor- Spawns the bundled engine (`node <gentle-pi>/bin/gentle-shell.mjs --home <dataDir>/agent --mode rpc --session-dir <dataDir>/sessions --append-system-prompt <identity file>`) with `cwd` = the assistant's own workspace, `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home. A custom `workspace` (config or `GENTLE_DOT_WORKSPACE`) is never used as `cwd` and nothing is written there; it is passed as one more `--append-system-prompt` text: "The user's preferred working folder is <path>. Use absolute paths there unless told otherwise."-- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.-- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`.-- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook checks `<agentHome>/mcp.json` against the hash in `<dataDir>/connectors.json` and restores it, then hands the approval guard its policy in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).+- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. `GENTLE_PI_AGENTS=0` turns Gentle Shell's subagents off (no `subagent_*` or `orchestrator_*` tools) until S25. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.+- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`. The memory server the engine starts there outlives the engine, so when nothing listened on the private port as the daemon started, the daemon stops it when it closes: the PID listening on that port (`lsof`), only when its `/health` `instance_id` matches `<dataDir>/home/.engram/.instance-id`.+- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook puts back the connector files from the daemon's in-memory state (§4, Connectors), then hands the approval guard its policy, also from memory, in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).- Parses stdout with strict LF framing on a byte stream. Never Node `readline` (it splits on U+2028/U+2029, which are valid inside JSON).- Correlates commands by `id`; stdout records without `id` are session events.- Reads stderr only as diagnostics (logged, never parsed).@@ -134,10 +134,12 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete### Connectors (S18)- Catalog (`packages/daemon/src/connectors.ts`): Notion `https://mcp.notion.com/mcp`, Linear `https://mcp.linear.app/mcp`, and Atlassian `https://mcp.atlassian.com/v2/mcp`, each remote OAuth, with a curated list of read-only tools. Slack, Gmail, Discord, assistant-drafted servers (S19), and imports (S20) add catalog entries or drafts that go through the same store.-- The daemon is the only writer of `<agentHome>/mcp.json`. It renders the file from `<dataDir>/connectors.json` (each connector's `enabled` and `mode`, plus the sha256 of the approved `mcp.json`), writes both atomically with mode 0600, and restores `mcp.json` before every agent start. Every server is `exposure: "direct"` (the assistant turns codemode off). "Read only" adds `toolExposure: {"*": "hidden", <curated tool>: "direct"}`; the engine prefers exact names over patterns, so an unknown tool stays hidden.+- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). "Read only" adds `toolExposure: {"*": "hidden", <curated tool>: "direct"}`; the engine prefers exact names over patterns, so an unknown tool stays hidden.- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<agentHome>`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).- Status: `connected` when `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (token values are dropped while parsing); `needs_signin` otherwise; `error` after a failed sign-in.-- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): a connector tool runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm` (an ask card: "Allow Notion to create pages?" with the key arguments, truncated), and is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks. `write`/`edit` of `mcp.json`, `mcp-auth.json`, `connectors.json`, or the guard itself (symlinks resolved), and commands that name those files, `PI_CODING_AGENT_DIR`, or `mcp add|login|logout|remove`, are blocked with a note to use the Connectors screen.+- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): a connector tool runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.+- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json`, `models.json` (it can hold API keys), `mcp.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.+- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines.### Switching and history races (S21)@@ -223,6 +225,7 @@ The UI shows one endless chat: no conversations list, no new conversation, and t- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon.## 9. Desktop shell contract (Tauri 2 <-> UI)diff --git a/e2e/web.spec.ts b/e2e/web.spec.tsindex 138acac..1d9d342 100644--- a/e2e/web.spec.ts+++ b/e2e/web.spec.ts@@ -281,6 +281,7 @@ test("shows a connector action as an approval card with a preview", async ({ pagawait expect(card).toContainText("parent: Team notes");await expect(card).toContainText("title: Weekly plan");await expect(card.locator(".ask-message")).toHaveCSS("white-space", "pre-wrap");+ await expect(card.locator(".ask-message")).toHaveCSS("overflow-y", "auto");await card.screenshot({ path: "/tmp/gentle-dot-t18a/approval-card.png" });await page.screenshot({ path: "/tmp/gentle-dot-t18a/approval-card-panel.png" });await card.getByRole("button", { name: "No" }).click();@@ -345,3 +346,18 @@ test("asks for the access key when there is none", async ({ page }) => {await page.goto("/");await expect(page.getByRole("status")).toContainText("This page needs your access key");});++test("keeps the onboarding banner in its own space, above the first message", async ({ page }) => {+ await page.setViewportSize({ width: 360, height: 300 });+ await open(page);+ for (const text of ["one", "two", "three"]) {+ await say(page, text);+ await expect(page.locator(".message-assistant").last()).toHaveText(`Echo: ${text}`);+ }+ const banner = page.locator(".onboarding");+ await expect(banner).toBeVisible();+ await page.screenshot({ path: "test-results/onboarding-banner.png" });+ const top = await banner.boundingBox();+ const first = await page.locator(".message").first().boundingBox();+ expect(top && first && top.y + top.height <= first.y).toBe(true);+});diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex f796404..029d0cd 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -120,7 +120,10 @@ export class DotBridge {});supervisor.onEvent((event) => this.onAgentEvent(event));if (options.auth) options.auth.onCredentialsChanged = () => this.afterCredentialsChange();- if (options.connectors) options.connectors.onChanged = (restart) => this.afterConnectorsChange(restart);+ if (options.connectors) {+ options.connectors.onChanged = (restart) => this.afterConnectorsChange(restart);+ options.connectors.onBlocked = () => this.connectorChangeBlocked();+ }this.state = this.deriveState();}@@ -476,6 +479,12 @@ export class DotBridge {if (refused) this.deliver(client, { type: "error", ...refused });}+ /** The connector files were changed outside the Connectors screen and put back. */+ private connectorChangeBlocked(): void {+ this.broadcast({ type: "toast", level: "warning", message: "A change to your connectors was blocked." });+ this.broadcast({ type: "connectors", connectors: this.requireConnectors().list() });+ }+/** Every window sees the new statuses; a new mcp.json needs an agent restart, once it is idle. */private afterConnectorsChange(restart: boolean): void {this.broadcast({ type: "connectors", connectors: this.requireConnectors().list() });@@ -686,6 +695,8 @@ export class DotBridge {this.onQueueUpdate(event);break;case "agent_settled":+ // The run may have changed the connector files.+ this.options.connectors?.enforce();this.runningTools.clear();this.assistantId = undefined;this.stopRequested = false;diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex e19e9bb..fc840da 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -1,6 +1,16 @@import { type ChildProcess, spawn } from "node:child_process";-import { createHash, randomUUID } from "node:crypto";-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { randomUUID } from "node:crypto";+import {+ existsSync,+ type FSWatcher,+ lstatSync,+ mkdirSync,+ readFileSync,+ renameSync,+ unlinkSync,+ watch,+ writeFileSync,+} from "node:fs";import { createRequire } from "node:module";import { join } from "node:path";import { fileURLToPath } from "node:url";@@ -123,8 +133,6 @@ export function renderMcpJson(state: ConnectorsState): string {return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;}-const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");-function writePrivate(path: string, text: string): void {const temp = `${path}.${process.pid}.tmp`;writeFileSync(temp, text, { mode: 0o600 });@@ -135,20 +143,29 @@ export interface ConnectorStoreOptions {dataDir: string;/** The engine's home, which holds `mcp.json` and `mcp-auth.json`. */agentHome: string;+ /** The engine's working folder; a project `.pi/mcp.json` there would add servers. */+ workspace?: string;/** The approval guard's own file, protected like the connector files. */guardPath?: string;log?: (line: string) => void;}/**- * The daemon's record of the connectors (`<data>/connectors.json`) and the only writer of the- * engine's `mcp.json`, which it renders from that record. The record keeps the hash of the- * approved `mcp.json`, so a file changed by anything else is put back before the engine starts.+ * The connectors the user approved. The daemon reads `<data>/connectors.json` once, when it+ * starts, and from then on the state lives in memory and changes only through the Connectors+ * screen. The files (`connectors.json`, the engine's `mcp.json`) are written from memory; a change+ * made by anything else (the assistant has a shell) is put back, and a project `.pi/mcp.json` in+ * the workspace is removed. Checked on every file event, before every engine start, and after+ * every run. A change made while the daemon is not running is loaded at its next start (stage 2, S25).*/export class ConnectorStore {readonly file: string;readonly mcpFile: string;readonly authFile: string;+ /** Called after a change made outside the Connectors screen was put back. */+ onReverted: () => void = () => {};+ private saved: ConnectorsState;+ private watchers: FSWatcher[] = [];private readonly options: ConnectorStoreOptions;constructor(options: ConnectorStoreOptions) {@@ -156,6 +173,7 @@ export class ConnectorStore {this.file = join(options.dataDir, "connectors.json");this.mcpFile = join(options.agentHome, "mcp.json");this.authFile = join(options.agentHome, "mcp-auth.json");+ this.saved = this.load();}get agentHome(): string {@@ -163,38 +181,82 @@ export class ConnectorStore {}state(): ConnectorsState {- return { connectors: this.read().connectors };+ return structuredClone(this.saved);}- /** Changes the record, then writes both files (each atomically, mode 0600). */+ /** Changes the state, then writes both files (each atomically, mode 0600). */update(change: (state: ConnectorsState) => void): void {const state = this.state();change(state);- const rendered = renderMcpJson(state);+ this.saved = state;mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(- this.file,- `${JSON.stringify({ version: 1, connectors: state.connectors, hash: sha256(rendered) }, null, 2)}\n`,- );- writePrivate(this.mcpFile, rendered);+ writePrivate(this.file, this.recordText());+ writePrivate(this.mcpFile, renderMcpJson(state));}- /** Puts the approved `mcp.json` back when it changed; true when it had to. */- ensureMcpJson(): boolean {- const saved = this.read();- const current = existsSync(this.mcpFile) ? readFileSync(this.mcpFile, "utf8") : undefined;- const nothingAdded = saved.hash === undefined && Object.keys(saved.connectors).length === 0;- if (current === undefined && nothingAdded) return false;- if (current !== undefined && saved.hash !== undefined && sha256(current) === saved.hash) return false;- const rendered = renderMcpJson({ connectors: saved.connectors });- mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(this.mcpFile, rendered);+ /**+ * Puts back every connector file that differs from the approved state; true when one did.+ * `report: false` only writes them (the daemon's start, where the files are what it just read).+ */+ enforce(report = true): boolean {+ const untouched = Object.keys(this.saved.connectors).length === 0;+ const changed: string[] = [];+ for (const [file, text] of [+ [this.file, this.recordText()],+ [this.mcpFile, renderMcpJson(this.saved)],+ ] as const) {+ const current = existsSync(file) ? readFileSync(file, "utf8") : undefined;+ if (current === text || (current === undefined && untouched)) continue;+ mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ writePrivate(file, text);+ changed.push(file);+ }+ if (this.removeProjectConfig()) changed.push("the workspace's .pi/mcp.json");+ if (changed.length === 0 || !report) return changed.length > 0;this.options.log?.(- "mcp.json was changed outside the Connectors screen; restored the approved connectors",+ `connector files were changed outside the Connectors screen; put back ${changed.join(", ")}`,);+ this.onReverted();return true;}+ /**+ * Puts changes back as soon as the files change (the folders are watched, so renames count).+ * File events on macOS can be missed right after a watch starts, so a check every second backs them up.+ */+ watch(): void {+ this.close();+ let timer: NodeJS.Timeout | undefined;+ const check = () => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ try {+ this.enforce();+ } catch (error) {+ this.options.log?.(`could not check the connector files: ${(error as Error).message}`);+ }+ this.watchProjectConfig();+ }, 20);+ };+ const folders = [this.options.dataDir, this.options.agentHome, this.options.workspace];+ for (const folder of folders) {+ if (!folder) continue;+ mkdirSync(folder, { recursive: true, mode: 0o700 });+ this.watchers.push(watch(folder, check));+ }+ this.check = check;+ this.watchProjectConfig();+ this.poll = setInterval(check, 1000);+ this.poll.unref();+ }++ close(): void {+ clearInterval(this.poll);+ for (const watcher of this.watchers.splice(0)) watcher.close();+ this.projectWatcher?.close();+ this.projectWatcher = undefined;+ }+/** What the approval guard enforces: the turned-on connectors and the files only the daemon writes. */policy(): ConnectorPolicy {const connectors: NonNullable<ConnectorPolicy["connectors"]> = {};@@ -205,10 +267,14 @@ export class ConnectorStore {}return {connectors,+ // Sign-ins and keys, connector state, and the daemon's access key.protectedPaths: [this.mcpFile,this.authFile,+ join(this.options.agentHome, "auth.json"),+ join(this.options.agentHome, "models.json"),this.file,+ join(this.options.dataDir, "token"),...(this.options.guardPath ? [this.options.guardPath] : []),],};@@ -231,11 +297,52 @@ export class ConnectorStore {}}- private read(): { connectors: ConnectorsState["connectors"]; hash?: string } {+ private check: () => void = () => {};+ private poll: NodeJS.Timeout | undefined;+ private projectWatcher: FSWatcher | undefined;++ /** `.pi` appears after the watch starts; its folder is watched once it is there. */+ private watchProjectConfig(): void {+ const folder = this.options.workspace && join(this.options.workspace, ".pi");+ if (this.projectWatcher || !folder || this.watchers.length === 0 || !isFolder(folder)) return;+ try {+ const watcher = watch(folder, this.check);+ watcher.on("error", () => {+ watcher.close();+ if (this.projectWatcher === watcher) this.projectWatcher = undefined;+ });+ this.projectWatcher = watcher;+ } catch {}+ }++ /** Removes `<workspace>/.pi/mcp.json`; a `.pi` that is a link loses the link, never what it points to. */+ private removeProjectConfig(): boolean {+ if (!this.options.workspace) return false;+ const folder = join(this.options.workspace, ".pi");+ const link = lstatOrUndefined(folder);+ if (link?.isSymbolicLink()) {+ const target = join(folder, "mcp.json");+ if (!existsSync(target)) return false;+ unlinkSync(folder);+ return true;+ }+ const file = join(folder, "mcp.json");+ const stat = link && lstatOrUndefined(file);+ if (!stat || stat.isDirectory()) return false;+ unlinkSync(file);+ this.projectWatcher?.close();+ this.projectWatcher = undefined;+ return true;+ }++ private recordText(): string {+ return `${JSON.stringify({ version: 1, connectors: this.saved.connectors }, null, 2)}\n`;+ }++ private load(): ConnectorsState {try {const saved = JSON.parse(readFileSync(this.file, "utf8")) as {connectors?: Record<string, { enabled?: unknown; mode?: unknown }>;- hash?: unknown;};const connectors: ConnectorsState["connectors"] = {};for (const [id, value] of Object.entries(saved.connectors ?? {})) {@@ -245,13 +352,23 @@ export class ConnectorStore {mode: value?.mode === "read_write" ? "read_write" : "read_only",};}- return { connectors, ...(typeof saved.hash === "string" ? { hash: saved.hash } : {}) };+ return { connectors };} catch {return { connectors: {} };}}}+function lstatOrUndefined(path: string) {+ try {+ return lstatSync(path);+ } catch {+ return undefined;+ }+}++const isFolder = (path: string) => lstatOrUndefined(path)?.isDirectory() === true;+/** How to run the engine's command line: `command ...args mcp <subcommand> <server>`. */export interface McpCli {command: string;@@ -320,12 +437,24 @@ export interface ConnectorManagerOptions {export class ConnectorManager {/** `restart`: the engine must restart (when idle) to read the new `mcp.json`. */onChanged: (restart: boolean) => void = () => {};+ /** A change to the connector files made outside the Connectors screen was put back. */+ onBlocked: () => void = () => {};private flow: Flow | undefined;private readonly failed = new Set<string>();private readonly options: ConnectorManagerOptions;constructor(options: ConnectorManagerOptions) {this.options = options;+ options.store.onReverted = () => this.onBlocked();+ }++ /** Puts back connector files changed outside the Connectors screen (for example after a run). */+ enforce(): void {+ try {+ this.options.store.enforce();+ } catch (error) {+ this.log(`could not check the connector files: ${(error as Error).message}`);+ }}list(): ConnectorInfo[] {@@ -531,7 +660,8 @@ export class ConnectorManager {}if (url.hostname === "localhost") url.hostname = "127.0.0.1";try {- await fetch(url, { signal: AbortSignal.timeout(10_000) });+ // Only this loopback address; where it redirects is not followed.+ await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000) });} catch {if (this.flow === flow) this.askForAddress(flow, true);}diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex e5a3993..7a6a48c 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -15,7 +15,7 @@ import {type McpCli,policyEnv,} from "./connectors.ts";-import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";+import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemory } from "./isolation.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";import { AgentSupervisor } from "./supervisor.ts";@@ -115,6 +115,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {: [];let agentEnv = { ...(options.agentEnv ?? process.env) };const homeArgs: string[] = [];+ const memory = options.agentHome ? await privateMemory(agentEnv, options.dataDir, log) : undefined;if (options.agentHome) {homeArgs.push("--home", options.agentHome);// The engine also writes under the home folder; it gets one of its own.@@ -122,9 +123,11 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");}const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);+ // The approved connectors are read once, here; the engine cannot change them (docs/design.md).const connectorStore = new ConnectorStore({dataDir: options.dataDir,agentHome,+ workspace: options.workspace,guardPath: APPROVAL_GUARD,log,});@@ -142,13 +145,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {cwd: options.workspace,dataDir: options.dataDir,env: agentEnv,- // mcp.json is read when a session starts: put back anything not approved, and hand the guard its policy.+ // mcp.json is read when a session starts: put back anything not approved, and hand the guard+ // its policy from the daemon's memory, never from the files.prepareSpawn: () => {- try {- connectorStore.ensureMcpJson();- } catch (error) {- log(`could not check mcp.json: ${(error as Error).message}`);- }+ connectors.enforce();return policyEnv(connectorStore);},// The first start in a new home installs the engine's companion packages.@@ -184,6 +184,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),});+ // The files as the daemon writes them (an older version kept a hash), then watched.+ connectorStore.enforce(false);+ connectorStore.watch();+const server = createServer((req, res) => handleHttp(req, res, options.uiDir, bridge));const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });let port = options.port;@@ -217,6 +221,8 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {wss.close();await new Promise<void>((done) => server.close(() => done()));await supervisor.stop();+ connectorStore.close();+ await memory?.stop();},};}diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.tsindex 487fe4c..98ce3e2 100644--- a/packages/daemon/src/extensions/approval-guard.ts+++ b/packages/daemon/src/extensions/approval-guard.ts@@ -11,12 +11,20 @@* daemon in this process's environment, which the assistant cannot change. Without a valid* policy nothing counts as read-only, so every connector call asks.*- * Connectors are the user's to change: writes, edits, and commands that touch the connector- * files or run `mcp add/login/logout/remove` are blocked with a note to use the Connectors screen.+ * Connectors are the user's to change: writes and edits of the connector files and commands that+ * run `mcp add/login/logout/remove` are blocked with a note to use the Connectors screen. The+ * credential and control files (sign-ins, keys, connector state, the daemon's access key) cannot be+ * read with the file tools either, by any path, symlink, or hard link.+ *+ * Commands are checked by text: one that names one of those files (by its name, with quotes+ * removed), the data folder, the keychain, or the engine's home variable is blocked. That check is+ * best effort, NOT a security boundary: the assistant runs as the user with a shell, so a command+ * can still build a name the check does not see. The daemon keeps the connector state in memory+ * and puts changed files back (docs/design.md, Connectors), and stage 2 (S25) moves tokens out of reach.* This file has no dependencies besides Node, so the engine loads it as is.*/-import { realpathSync } from "node:fs";-import { basename, dirname, isAbsolute, join, resolve } from "node:path";+import { realpathSync, statSync } from "node:fs";+import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";export const POLICY_ENV = "GENTLE_DOT_CONNECTOR_POLICY";@@ -26,7 +34,7 @@ export type ConnectorMode = "read_only" | "read_write";export interface ConnectorPolicy {/** Approved connectors by server name; undefined when the policy is missing or invalid. */connectors?: Record<string, { name: string; mode: ConnectorMode; readOnlyTools: string[] }>;- /** Files only the daemon may change. */+ /** Files only the daemon may read or change: credentials and connector control files. */protectedPaths: string[];}@@ -46,16 +54,25 @@ export interface GuardCall {const USE_CONNECTORS_SCREEN ="Connectors are managed by the user in the Connectors screen. Ask the user to make this change there.";+const PRIVATE_FILE =+ "That file holds the user's private sign-ins or settings, so the assistant cannot use it. Connectors are managed by the user in the Connectors screen; for anything else there, ask the user.";const DECLINED = "The user did not allow this action. Do not try it again unless the user asks.";const NO_UI = "This action needs the user's approval, and no one can approve it right now.";const CONNECTOR_COMMAND = /\bmcp\s+(?:add|login|logout|remove)\b/;+/** Reads of the macOS keychain. */+const KEYCHAIN_COMMAND = /\bsecurity\s+(?:find-(?:generic|internet)-password|dump-keychain|export)\b/;+/** Names a command must not mention: the engine's home variable and the data folder. */+const PRIVATE_NAMES = ["pi_coding_agent_dir", ".gentle-dot"];+/** The engine's file tools, by the path they take. */+const FILE_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls"]);+const COMMAND_TOOLS = new Set(["bash", "powershell"]);/** Arguments that say where an action goes and what it says, shown first in the preview. */const KEY_FIELDS = [/^(to|cc|bcc|recipients?|channel|chat|parent|page|database|space|project|team|issue|title|subject|name)/i,/^(body|text|content|message|comment|description|markdown)/i,];-const MAX_FIELDS = 6;-const MAX_VALUE = 160;+/** The preview shows every argument, up to this many characters. */+const PREVIEW_LIMIT = 8000;/** Like the engine's tool names: everything but letters, digits, and `_` becomes `_`. */const toolId = (server: string, tool: string) => `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, "_");@@ -100,19 +117,23 @@ export function parsePolicy(raw: string | undefined): ConnectorPolicy | undefineexport function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecision {const { toolName, input } = call;- if (toolName === "write" || toolName === "edit") {- const path = input.path ?? input.file_path;- if (typeof path === "string" && isProtected(resolvePath(path, call.cwd), policy.protectedPaths))- return { action: "block", reason: USE_CONNECTORS_SCREEN };- return { action: "pass" };+ if (FILE_TOOLS.has(toolName)) {+ const raw = input.path ?? input.file_path;+ const target = resolvePath(typeof raw === "string" && raw !== "" ? raw : ".", call.cwd);+ const touches =+ isProtected(target, policy.protectedPaths) ||+ // A search reads every file below its folder.+ (toolName === "grep" && policy.protectedPaths.some((path) => isInside(path, target)));+ if (!touches) return { action: "pass" };+ const writes = toolName === "write" || toolName === "edit";+ return { action: "block", reason: writes ? USE_CONNECTORS_SCREEN : PRIVATE_FILE };}- if (toolName === "bash") {+ if (COMMAND_TOOLS.has(toolName)) {const command = typeof input.command === "string" ? input.command : "";- const touches =- CONNECTOR_COMMAND.test(command) ||- command.includes("PI_CODING_AGENT_DIR") ||- policy.protectedPaths.flatMap(spellings).some((path) => command.includes(path));- return touches ? { action: "block", reason: USE_CONNECTORS_SCREEN } : { action: "pass" };+ if (CONNECTOR_COMMAND.test(command)) return { action: "block", reason: USE_CONNECTORS_SCREEN };+ return namesPrivateFile(command, policy.protectedPaths)+ ? { action: "block", reason: PRIVATE_FILE }+ : { action: "pass" };}if (!toolName.startsWith("mcp__")) return { action: "pass" };@@ -138,9 +159,7 @@ export function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecisionreturn {action: "ask",title: `Allow ${name} to ${action}?`,- message: [`The assistant wants to ${action} in ${name}.`, "", ...previewLines(input)]- .join("\n")- .trimEnd(),+ message: `The assistant wants to ${action} in ${name}.\n\n${preview(input)}`.trimEnd(),};}@@ -152,27 +171,66 @@ function describeAction(toolName: string, server: string): string {return words ? words.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase() : "use a tool";}-function previewLines(input: Record<string, unknown>): string[] {+/** Every argument, key fields first, so the user approves what they saw; very long ones say what was cut. */+function preview(input: Record<string, unknown>): string {const rank = (key: string) => {const index = KEY_FIELDS.findIndex((pattern) => pattern.test(key));return index < 0 ? KEY_FIELDS.length : index;};- const keys = Object.keys(input).sort((a, b) => rank(a) - rank(b));- const lines = keys.slice(0, MAX_FIELDS).map((key) => `${key}: ${shorten(input[key])}`);- if (keys.length > MAX_FIELDS) lines.push(`…and ${keys.length - MAX_FIELDS} more`);- return lines;+ const text = Object.keys(input)+ .sort((a, b) => rank(a) - rank(b))+ .map((key) => `${key}: ${show(input[key])}`)+ .join("\n");+ if (text.length <= PREVIEW_LIMIT) return text;+ return `${text.slice(0, PREVIEW_LIMIT)}\n(truncated, ${text.length - PREVIEW_LIMIT} more characters)`;}-function shorten(value: unknown): string {- const text = typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));- const short = text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}…` : text;+function show(value: unknown): string {+ const text = typeof value === "string" ? value : (JSON.stringify(value, null, 2) ?? String(value));// Lines inside one value are indented, so they do not read as fields of their own.- return short.replace(/\n/g, "\n ");+ return text.replace(/\n/g, "\n ");+}++/**+ * True when a command mentions a private file by name (quotes, backslashes, and string+ * concatenation removed, any case), the data folder, the engine's home variable, or the keychain.+ * Best effort: a shell can always spell a name some other way.+ */+function namesPrivateFile(command: string, protectedPaths: string[]): boolean {+ const text = command+ .replace(/(["'`])\s*\+\s*(["'`])/g, "")+ .replace(/["'`\\]/g, "")+ .toLowerCase();+ if (KEYCHAIN_COMMAND.test(text) || PRIVATE_NAMES.some((name) => text.includes(name))) return true;+ const words = text.split(/[\s;|&()<>=,+]+/).map((word) => word.slice(word.lastIndexOf("/") + 1));+ return protectedPaths.some((path) => {+ const name = basename(path).toLowerCase();+ // A name without a dot (`token`) counts only as a word of its own, not inside `$GITHUB_TOKEN`.+ if (name.includes(".") ? text.includes(name) : words.includes(name)) return true;+ return words.some(+ (word) => /[*?[]/.test(word) && word.replace(/[*?[\]]/g, "").length >= 3 && glob(word).test(name),+ );+ });}+/** A shell pattern (`mcp-a*`) as a regular expression for one file name. */+function glob(pattern: string): RegExp {+ const source = pattern+ .replace(/[.+^${}()|\\]/g, "\\$&")+ .replace(/\*/g, ".*")+ .replace(/\?/g, ".");+ try {+ return new RegExp(`^${source}$`);+ } catch {+ return /^$/;+ }+}++/** Like the engine: `@` in front is dropped, `~` is the home folder, relative paths start at `cwd`. */function resolvePath(path: string, cwd: string): string {const home = process.env.HOME;- const expanded = home && (path === "~" || path.startsWith("~/")) ? `${home}${path.slice(1)}` : path;+ const bare = path.startsWith("@") ? path.slice(1) : path;+ const expanded = home && (bare === "~" || bare.startsWith("~/")) ? `${home}${bare.slice(1)}` : bare;return isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded);}@@ -190,16 +248,39 @@ function spellings(path: string): string[] {return real === absolute ? [absolute] : [absolute, real];}+/** The same file by name (any case: macOS and Windows folders usually ignore it), symlink, or hard link. */function isProtected(path: string, protectedPaths: string[]): boolean {- // macOS and Windows folders usually ignore case.const candidates = spellings(path).map((p) => p.toLowerCase());- return protectedPaths.some((p) => spellings(p).some((s) => candidates.includes(s.toLowerCase())));+ const id = fileId(path);+ return protectedPaths.some(+ (p) =>+ spellings(p).some((s) => candidates.includes(s.toLowerCase())) ||+ (id !== undefined && fileId(p) === id),+ );+}++/** True when `file` is below `folder`. */+function isInside(file: string, folder: string): boolean {+ return spellings(file).some((f) =>+ spellings(folder).some((d) => f.toLowerCase().startsWith((d.endsWith(sep) ? d : d + sep).toLowerCase())),+ );+}++function fileId(path: string): string | undefined {+ try {+ const stat = statSync(path);+ return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;+ } catch {+ return undefined;+ }}export default function approvalGuard(pi: ExtensionAPI): void {const parsed = parsePolicy(process.env[POLICY_ENV]);const agentDir = process.env.PI_CODING_AGENT_DIR;- const fallback = agentDir ? [resolve(agentDir, "mcp.json"), resolve(agentDir, "mcp-auth.json")] : [];+ const fallback = agentDir+ ? ["mcp.json", "mcp-auth.json", "auth.json", "models.json"].map((name) => resolve(agentDir, name))+ : [];const policy: ConnectorPolicy = parsed ?? { protectedPaths: fallback };pi.on("tool_call", async (event, ctx) => {diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex d2e4616..8e41b24 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -1,4 +1,5 @@-import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";+import { execFile } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";@@ -41,6 +42,7 @@ export function ensureMemoryProject(workspace: string): void {* user's server. The user's own `ENGRAM_PORT` and `ENGRAM_URL` are kept.* `GENTLE_DOT_ENGRAM=private` instead runs a memory of its own under the* engine's home, on port 7438 (`GENTLE_DOT_ENGRAM_PORT` overrides it).+ * Subagents are off (`GENTLE_PI_AGENTS=0`) until S25.*/export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeJS.ProcessEnv {const home = join(dataDir, "home");@@ -55,6 +57,9 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeXDG_STATE_HOME: join(home, ".local", "state"),};for (const key of INHERITED_HOMES) delete env[key];+ // Subagent child engines do not load the approval guard, so subagents stay off until the+ // daemon enforces connectors itself (S25).+ env.GENTLE_PI_AGENTS = "0";if (base.GENTLE_DOT_ENGRAM === "private") {env.ENGRAM_PORT = base.GENTLE_DOT_ENGRAM_PORT || PRIVATE_ENGRAM_PORT;delete env.ENGRAM_URL;@@ -67,3 +72,53 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): Nodeif (!base.GIT_CONFIG_GLOBAL && existsSync(gitConfig)) env.GIT_CONFIG_GLOBAL = gitConfig;return env;}++/**+ * In private memory mode (`GENTLE_DOT_ENGRAM=private`) the engine's memory plugin starts a memory+ * server on the private port, and it outlives the engine. When nothing listened on that port as the+ * daemon started, the daemon caused it, so `stop()` ends it when the daemon closes: the PID that+ * listens on the port, and only after its `/health` instance id matches the private data folder's+ * (`<dataDir>/home/.engram/.instance-id`). Undefined outside private mode or when it already ran.+ */+export async function privateMemory(+ base: NodeJS.ProcessEnv,+ dataDir: string,+ log: (line: string) => void,+): Promise<{ stop(): Promise<void> } | undefined> {+ if (base.GENTLE_DOT_ENGRAM !== "private") return undefined;+ const port = base.GENTLE_DOT_ENGRAM_PORT || PRIVATE_ENGRAM_PORT;+ if ((await listeningPid(port)) !== undefined) return undefined;+ return {+ async stop() {+ const pid = await listeningPid(port);+ if (pid === undefined) return;+ let expected: string;+ try {+ expected = readFileSync(join(dataDir, "home", ".engram", ".instance-id"), "utf8").trim();+ } catch {+ return;+ }+ const health = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) })+ .then((response) => response.json() as Promise<{ instance_id?: unknown }>)+ .catch(() => undefined);+ if (!expected || health?.instance_id !== expected) {+ log(`the memory server on port ${port} serves other data; left running`);+ return;+ }+ try {+ process.kill(pid, "SIGTERM");+ log(`stopped the private memory server (pid ${pid})`);+ } catch {}+ },+ };+}++/** The one PID listening on `port` on this computer (`lsof`), if any. */+function listeningPid(port: string): Promise<number | undefined> {+ return new Promise((resolve) => {+ execFile("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"], (error, stdout) => {+ const pids = [...new Set(String(stdout).trim().split("\n").filter(Boolean))];+ resolve(!error && pids.length === 1 && /^\d+$/.test(pids[0] ?? "") ? Number(pids[0]) : undefined);+ });+ });+}diff --git a/packages/daemon/test/approval-guard-engine.test.ts b/packages/daemon/test/approval-guard-engine.test.tsindex ee5c4b0..96a43fb 100644--- a/packages/daemon/test/approval-guard-engine.test.ts+++ b/packages/daemon/test/approval-guard-engine.test.ts@@ -83,6 +83,10 @@ function startEngine(port: number) {},}),);+ writeFileSync(+ join(agentDir, "mcp-auth.json"),+ JSON.stringify({ "mcp__fake|x": { tokens: { access_token: "secret-token-value" } } }),+ );const mcpFile = join(agentDir, "mcp.json");writeFileSync(mcpFile,@@ -189,4 +193,30 @@ describe.skipIf(!engineAvailable)("approval guard in the real engine", () => {1,);}, 60_000);++ it("keeps the connector sign-ins away from the read tool and from shell commands", async () => {+ const model = await fakeModel([+ { name: "mcp__fake__list_messages", args: {} },+ { name: "read", args: { path: "../agent/mcp-auth.json" } },+ { name: "bash", args: { command: `cd ..; cat agent/"mcp-"'auth.json'` } },+ ]);+ cleanups.push(() => model.close());+ const { records, send, stderr } = startEngine((model.address() as AddressInfo).port);+ send({ type: "get_state", id: "s" });+ await waitFor(() => records.find((r) => r.id === "s"), 20_000).catch(() => {+ throw new Error(`the engine did not start: ${stderr().slice(-800)}`);+ });+ let prompts = 0;+ const ends = await waitFor(() => {+ const found = records.filter((r) => r.type === "tool_execution_end");+ if (found.length >= 3) return found;+ if (records.filter((r) => r.type === "agent_settled").length >= prompts)+ send({ type: "prompt", id: `p${prompts++}`, message: "show me the sign-ins" });+ return undefined;+ }, 20_000);+ const byTool = Object.fromEntries(ends.map((r) => [r.toolName, r]));+ expect(byTool.read?.isError).toBe(true);+ expect(byTool.bash?.isError).toBe(true);+ expect(JSON.stringify(records)).not.toContain("secret-token-value");+ }, 60_000);});diff --git a/packages/daemon/test/approval-guard.test.ts b/packages/daemon/test/approval-guard.test.tsindex a40c732..5ad2b39 100644--- a/packages/daemon/test/approval-guard.test.ts+++ b/packages/daemon/test/approval-guard.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, realpathSync, symlinkSync } from "node:fs";+import { linkSync, mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";@@ -50,10 +50,11 @@ describe("approval guard decisions", () => {}});- it("asks before any other connector tool, with a readable, truncated preview", () => {+ it("asks before any other connector tool, with the full arguments as the preview", () => {const body = `Hello team,\n${"x".repeat(400)}`;+ const extra = Object.fromEntries(["a", "b", "c", "d", "e", "f"].map((key) => [key, key.repeat(3)]));const decision = decide(- call("mcp__notion__notion_create_pages", { parent: "Weekly notes", title: "Plan", body, icon: "🚀" }),+ call("mcp__notion__notion_create_pages", { ...extra, parent: "Weekly notes", title: "Plan", body }),policy(),);expect(decision.action).toBe("ask");@@ -62,14 +63,28 @@ describe("approval guard decisions", () => {expect(decision.message).toContain("The assistant wants to create pages in Notion.");expect(decision.message).toContain("parent: Weekly notes");expect(decision.message).toContain("title: Plan");- expect(decision.message).toContain("body: Hello team,\n xxx");- expect(decision.message).toContain("…");- expect(decision.message).not.toContain("x".repeat(300));+ // Every field and every character the user approves is shown.+ expect(decision.message).toContain(`body: Hello team,\n ${"x".repeat(400)}`);+ for (const key of Object.keys(extra)) expect(decision.message).toContain(`${key}: ${key.repeat(3)}`);+ expect(decision.message).not.toContain("more");+ expect(decision.message).not.toContain("…");// Key fields come before the rest.- expect(decision.message.indexOf("parent:")).toBeLessThan(decision.message.indexOf("icon:"));+ expect(decision.message.indexOf("parent:")).toBeLessThan(decision.message.indexOf("a: aaa"));expect(decision.message).not.toMatch(/gentle|\bpi\b|mcp__/i);});+ it("says how much of a very long preview was cut", () => {+ const decision = decide(call("mcp__notion__notion_create_pages", { body: "y".repeat(9000) }), policy());+ if (decision.action !== "ask") throw new Error("expected a question");+ const preview = decision.message.slice(decision.message.indexOf("body: "));+ expect(preview).toContain("y".repeat(7000));+ expect(preview).toMatch(/\n\(truncated, \d+ more characters\)$/);+ const shown = preview.split("\n(truncated")[0] ?? "";+ const more = Number(/truncated, (\d+) more/.exec(preview)?.[1]);+ expect(shown.length).toBe(8000);+ expect(shown.length + more).toBe("body: ".length + 9000);+ });+it("asks when a curated tool does not declare itself read-only", () => {expect(decide(call("mcp__notion__notion_fetch", { id: "p1" }), policy()).action).toBe("ask");expect(decide(call("mcp__notion__notion_fetch", { id: "p1" }, false), policy()).action).toBe("ask");@@ -99,7 +114,7 @@ describe("approval guard decisions", () => {});it("leaves ordinary tools alone", () => {- expect(decide(call("read", { path: `${AGENT}/mcp.json` }), policy())).toEqual({ action: "pass" });+ expect(decide(call("read", { path: "notes.md" }), policy())).toEqual({ action: "pass" });expect(decide(call("bash", { command: "ls -la" }), policy())).toEqual({ action: "pass" });expect(decide(call("write", { path: "notes.md", content: "mcp.json" }), policy())).toEqual({action: "pass",@@ -157,6 +172,111 @@ describe("approval guard decisions", () => {});});+/** A data folder like the assistant's: credentials and control files next to the agent's workspace. */+function credentialTree() {+ const data = mkdtempSync(join(tmpdir(), "guard-data-"));+ const agent = join(data, "agent");+ const workspace = join(data, "workspace");+ mkdirSync(agent);+ mkdirSync(workspace);+ const files = {+ auth: join(agent, "auth.json"),+ mcpAuth: join(agent, "mcp-auth.json"),+ models: join(agent, "models.json"),+ mcp: join(agent, "mcp.json"),+ connectors: join(data, "connectors.json"),+ token: join(data, "token"),+ };+ for (const file of Object.values(files)) writeFileSync(file, '{"secret":"value"}');+ const guarded: ConnectorPolicy = { connectors: {}, protectedPaths: Object.values(files) };+ const at = (toolName: string, input: Record<string, unknown>) => ({ toolName, input, cwd: workspace });+ return { data, agent, workspace, files, guarded, at };+}++describe("credential and control files (B2)", () => {+ it("blocks reading them with the read tool, by any path spelling", () => {+ const { files, guarded, at, workspace, data } = credentialTree();+ symlinkSync(files.mcpAuth, join(workspace, "notes.json"));+ linkSync(files.auth, join(workspace, "copy.json"));+ for (const path of [+ "../agent/mcp-auth.json",+ files.mcpAuth,+ realpathSync(files.mcpAuth),+ `@../agent/mcp-auth.json`,+ "../agent/./../agent/MCP-AUTH.JSON",+ "../agent/auth.json",+ "../agent/models.json",+ "../agent/mcp.json",+ "../connectors.json",+ "../token",+ `${data}/token`,+ "notes.json",+ "copy.json",+ ]) {+ expect(decide(at("read", { path }), guarded), path).toEqual({+ action: "block",+ reason: expect.stringContaining("private"),+ });+ }+ writeFileSync(join(workspace, "plan.md"), "# Plan");+ expect(decide(at("read", { path: "plan.md" }), guarded)).toEqual({ action: "pass" });+ expect(decide(at("read", { path: "../agent/settings.json" }), guarded)).toEqual({ action: "pass" });+ });++ it("blocks file tools that would show them: grep over them or a folder above them, find and ls on them", () => {+ const { guarded, at } = credentialTree();+ for (const [toolName, input] of [+ ["grep", { pattern: "access_token", path: "../agent/mcp-auth.json" }],+ ["grep", { pattern: "access_token", path: ".." }],+ ["grep", { pattern: "access_token", path: "../agent" }],+ ["find", { pattern: "*", path: "../agent/mcp-auth.json" }],+ ["ls", { path: "../agent/auth.json" }],+ ] as const) {+ expect(decide(at(toolName, input), guarded).action, `${toolName} ${input.path}`).toBe("block");+ }+ expect(decide(at("grep", { pattern: "todo" }), guarded)).toEqual({ action: "pass" });+ expect(decide(at("grep", { pattern: "todo", path: "." }), guarded)).toEqual({ action: "pass" });+ expect(decide(at("ls", { path: "../agent" }), guarded)).toEqual({ action: "pass" });+ expect(decide(at("find", { pattern: "*.md" }), guarded)).toEqual({ action: "pass" });+ });++ it("blocks commands that name them, however the name is written (best effort)", () => {+ const { guarded, at } = credentialTree();+ for (const command of [+ "cat ../agent/mcp-auth.json",+ "cd ..; cat agent/mcp-auth.json",+ `cat ../agent/"mcp-"'auth.json'`,+ "cat ../agent/mcp-\\auth.json",+ "cat ../agent/MCP-AUTH.JSON",+ `python3 -c "print(open('../agent/mcp-auth.json').read())"`,+ `node -e "console.log(require('fs').readFileSync('../agent/' + 'mcp-auth.json', 'utf8'))"`,+ `python3 -c "import os; print(open(os.path.join('..', 'agent', 'auth' + '.json')).read())"`,+ "ln -s ../agent/mcp-auth.json x && cat x",+ "cat ../agent/mcp-a*",+ "cat ../agent/models.json",+ "cp ../connectors.json /tmp/c",+ "cat ../token",+ "cat ~/.gentle-dot/agent/settings.json",+ "security find-generic-password -s notion -w",+ "echo $PI_CODING_AGENT_DIR",+ ]) {+ expect(decide(at("bash", { command }), guarded), command).toEqual({+ action: "block",+ reason: expect.stringContaining("private"),+ });+ }+ for (const command of [+ "ls -la",+ "cat README.md",+ "git status",+ "grep -rn todo src",+ 'curl -H "Authorization: Bearer $GITHUB_TOKEN" https://api.github.com',+ ]) {+ expect(decide(at("bash", { command }), guarded), command).toEqual({ action: "pass" });+ }+ });+});+type Handler = (event: Record<string, unknown>, ctx: unknown) => Promise<unknown> | unknown;function fakePi(tools: { name: string; annotations?: Record<string, boolean> }[]) {diff --git a/packages/daemon/test/connector-probe.test.ts b/packages/daemon/test/connector-probe.test.tsnew file mode 100644index 0000000..47fbc15--- /dev/null+++ b/packages/daemon/test/connector-probe.test.ts@@ -0,0 +1,259 @@+// @real-agent connector probe (L47 B1, T22): the daemon's command line with the bundled engine, a+// stand-in model (OpenAI-compatible, 127.0.0.1), a stand-in MCP server, a temporary HOME and data+// folder, and a private memory server on a free port. The model makes the agent edit the connector+// files from its workspace with one shell command (names built from variables, so the guard's text+// check does not see them), then end its own engine (`kill $PPID`). After the restart it tries+// Notion, which the user had turned off. The daemon must keep it off, put the files back, and say so.+// Opt-in (it installs the engine's companion packages on the first start and needs `engram` and `lsof`):+// GENTLE_DOT_CONNECTOR_PROBE=1 npx vitest run packages/daemon/test/connector-probe.test.ts+// GENTLE_DOT_PROBE_CLI points at another daemon command line (for example a copy of an older+// commit), and GENTLE_DOT_PROBE_EXPECT=enabled asserts that the attack works there.+import { type ChildProcess, execFileSync, spawn } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { createServer as createHttpServer } from "node:http";+import { createServer } from "node:net";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import type { ServerMessage } from "@gentle-dot/protocol";+import { describe, expect, it } from "vitest";+import WebSocket from "ws";+import { tempDir, waitFor } from "./helpers.ts";++const CLI = process.env.GENTLE_DOT_PROBE_CLI ?? fileURLToPath(new URL("../src/cli.ts", import.meta.url));+const FAKE_SERVER = fileURLToPath(new URL("./fixtures/fake-mcp-server.ts", import.meta.url));+const enabled = process.env.GENTLE_DOT_CONNECTOR_PROBE === "1";+const expectAttack = process.env.GENTLE_DOT_PROBE_EXPECT === "enabled";++type Rec = Record<string, unknown>;++function freePort(): Promise<number> {+ return new Promise((resolve) => {+ const server = createServer();+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as { port: number };+ server.close(() => resolve(port));+ });+ });+}++/** The one shell command of the attack: Notion on, pointed at the stand-in server, then `kill $PPID`. */+function attackCommand(): string {+ const mcp = JSON.stringify({+ mcpServers: { notion: { command: process.execPath, args: [FAKE_SERVER], exposure: "direct" } },+ });+ return [+ "j=.json; C=../conn; E=ectors; C=$C$E$j; M=../agent/mc; P=p; M=$M$P$j",+ `printf '%s' '${mcp}' > $M`,+ "H=$(shasum -a 256 $M | cut -d' ' -f1)",+ `printf '{"version":1,"connectors":{"notion":{"enabled":true,"mode":"read_write"}},"hash":"%s"}' $H > $C`,+ "mkdir -p .pi && cp $M .pi/",+ "kill $PPID",+ ].join("\n");+}++/** The stand-in model: "attack" runs the shell command, "search" calls Notion's search when offered. */+function fakeModel(toolLists: string[][]) {+ return createHttpServer((req, res) => {+ let body = "";+ req.on("data", (chunk: Buffer) => {+ body += chunk.toString("utf8");+ });+ req.on("end", () => {+ const request = JSON.parse(body) as {+ tools?: { function?: { name?: string } }[];+ messages?: { role: string; content?: unknown }[];+ };+ const tools = (request.tools ?? []).map((tool) => tool.function?.name ?? "");+ toolLists.push(tools);+ const last = request.messages?.at(-1);+ const text = typeof last?.content === "string" ? last.content : JSON.stringify(last?.content ?? "");+ res.writeHead(200, { "Content-Type": "text/event-stream" });+ const chunk = (delta: Rec, finish: string | null) =>+ res.write(+ `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 0, model: "fake-model", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`,+ );+ const call = (name: string, args: Rec) => {+ chunk(+ {+ role: "assistant",+ tool_calls: [+ {+ index: 0,+ id: `call_${Date.now()}`,+ type: "function",+ function: { name, arguments: JSON.stringify(args) },+ },+ ],+ },+ null,+ );+ chunk({}, "tool_calls");+ };+ if (last?.role === "user" && text.includes("attack")) call("bash", { command: attackCommand() });+ else if (+ last?.role === "user" &&+ text.includes("search") &&+ tools.includes("mcp__notion__notion_search")+ )+ call("mcp__notion__notion_search", { query: "plans" });+ else {+ chunk({ role: "assistant", content: last?.role === "tool" ? "Done." : "No Notion tools." }, null);+ chunk({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ });+ });+}++function listener(port: number): number | undefined {+ try {+ const pid = execFileSync("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"])+ .toString()+ .trim();+ return /^\d+$/.test(pid) ? Number(pid) : undefined;+ } catch {+ return undefined;+ }+}++describe.skipIf(!enabled)("@real-agent connector probe", () => {+ it("keeps a connector the user turned off turned off after the agent edits the files and restarts itself", {+ timeout: 400_000,+ }, async () => {+ const home = tempDir();+ const dataDir = join(tempDir(), "data");+ const agentHome = join(dataDir, "agent");+ const workspace = join(dataDir, "workspace");+ const calls = join(tempDir(), "server-calls.jsonl");+ mkdirSync(agentHome, { recursive: true });+ const toolLists: string[][] = [];+ const model = fakeModel(toolLists);+ const modelPort = await freePort();+ await new Promise<void>((resolve) => model.listen(modelPort, "127.0.0.1", resolve));+ writeFileSync(+ join(agentHome, "models.json"),+ JSON.stringify({+ providers: {+ fakeprov: {+ baseUrl: `http://127.0.0.1:${modelPort}/v1`,+ api: "openai-completions",+ apiKey: "not-a-key",+ models: [{ id: "fake-model" }],+ },+ },+ }),+ );+ writeFileSync(+ join(agentHome, "settings.json"),+ JSON.stringify({ defaultProvider: "fakeprov", defaultModel: "fake-model" }),+ );+ // The user added Notion earlier and turned it off.+ writeFileSync(+ join(dataDir, "connectors.json"),+ JSON.stringify({ version: 1, connectors: { notion: { enabled: false, mode: "read_only" } } }),+ );+ const memoryPort = await freePort();+ const child: ChildProcess = spawn(process.execPath, [CLI], {+ env: {+ PATH: process.env.PATH,+ HOME: home,+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_PORT: "0",+ GENTLE_DOT_ENGRAM: "private",+ GENTLE_DOT_ENGRAM_PORT: String(memoryPort),+ FAKE_MCP_SERVER_CALLS: calls,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ child.stdout?.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ child.stderr?.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ const exited = new Promise<void>((resolve) => child.on("close", () => resolve()));+ const messages: ServerMessage[] = [];+ try {+ await waitFor(() => /Gentle Dot is running|failed to start/.test(output), 300_000);+ const port = /127\.0\.0\.1:(\d+)/.exec(output)?.[1];+ const health = async () =>+ ((await (await fetch(`http://127.0.0.1:${port}/health`)).json()) as { agentState: string })+ .agentState;+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ const token = readFileSync(join(dataDir, "token"), "utf8").trim();+ ws.send(JSON.stringify({ type: "hello", token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"), 10_000);+ const settle = async () => {+ for (;;) {+ await new Promise((resolve) => setTimeout(resolve, 500));+ if ((await health().catch(() => "")) === "idle") return;+ }+ };+ await settle();++ ws.send(JSON.stringify({ type: "send", text: "attack" }));+ await waitFor(() => messages.some((m) => m.type === "interrupted"), 120_000);+ await settle();+ ws.send(JSON.stringify({ type: "send", text: "search" }));+ await waitFor(() => messages.some((m) => m.type === "agent_state" && m.state === "thinking"), 30_000);+ await settle();++ const serverCalls = existsSync(calls)+ ? readFileSync(calls, "utf8").trim().split("\n").filter(Boolean)+ : [];+ const summary = {+ cli: CLI,+ serverCalls,+ asks: messages.filter((m) => m.type === "ask").length,+ toasts: messages.flatMap((m) => (m.type === "toast" ? [m.message] : [])),+ connectorsJson: readFileSync(join(dataDir, "connectors.json"), "utf8"),+ mcpJson: readFileSync(join(agentHome, "mcp.json"), "utf8"),+ projectMcpJson: existsSync(join(workspace, ".pi", "mcp.json")),+ subagentTools: [...new Set(toolLists.flat().filter((name) => name.startsWith("subagent_")))],+ toolsOffered: [...new Set(toolLists.flat())].sort(),+ };+ console.log(`connector probe:\n${JSON.stringify(summary, null, 2)}`);+ ws.close();+ if (expectAttack) {+ expect(serverCalls.some((line) => line.includes("notion-search"))).toBe(true);+ expect(summary.asks).toBe(0);+ return;+ }+ expect(serverCalls).toEqual([]);+ expect(JSON.parse(summary.connectorsJson)).toEqual({+ version: 1,+ connectors: { notion: { enabled: false, mode: "read_only" } },+ });+ expect(JSON.parse(summary.mcpJson).mcpServers.notion).toMatchObject({+ url: "https://mcp.notion.com/mcp",+ exposure: "direct",+ enabled: false,+ });+ expect(summary.projectMcpJson).toBe(false);+ expect(summary.toasts).toContain("A change to your connectors was blocked.");+ // A1: subagents are off until S25 (their child engines do not load the approval guard).+ expect(summary.toolsOffered).toContain("bash");+ expect(summary.subagentTools).toEqual([]);+ } finally {+ if (child.exitCode === null) child.kill("SIGTERM");+ await exited;+ model.close();+ // The private memory server: stopped by the daemon (A4); if one is still there, stop it by+ // PID, only after checking it serves this probe's data folder.+ const pid = listener(memoryPort);+ const idFile = join(dataDir, "home", ".engram", ".instance-id");+ const expected = existsSync(idFile) ? readFileSync(idFile, "utf8").trim() : undefined;+ const served = await fetch(`http://127.0.0.1:${memoryPort}/health`)+ .then((r) => r.json() as Promise<{ instance_id?: string }>)+ .catch(() => undefined);+ if (pid && expected && served?.instance_id === expected) process.kill(pid, "SIGTERM");+ console.log(+ `private memory on ${memoryPort}: still listening after close: ${pid ?? "no"}; stopped by the probe: ${Boolean(pid && expected && served?.instance_id === expected)}`,+ );+ console.log(output.slice(-3000));+ }+ });+});diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.tsindex 162e761..8fc3a11 100644--- a/packages/daemon/test/connectors-gateway.test.ts+++ b/packages/daemon/test/connectors-gateway.test.ts@@ -1,4 +1,4 @@-import { readFileSync, writeFileSync } from "node:fs";+import { existsSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";import { fileURLToPath } from "node:url";import type { ServerMessage } from "@gentle-dot/protocol";@@ -147,7 +147,58 @@ describe("connectors over the protocol", () => {writeFileSync(file, JSON.stringify({ mcpServers: { evil: { command: "sh", args: ["-c", "id"] } } }));await d.supervisor.restart();expect(readFileSync(file, "utf8")).toBe(approved);- expect(logs.some((l) => l.includes("restored"))).toBe(true);+ expect(logs.some((l) => l.includes("put back"))).toBe(true);+ });++ it("keeps a connector the user turned off turned off when the agent edits the files and ends itself (B1)", async () => {+ const { d, send, find, messages, dataDir, agentHome, agentEnv } = await setup({ cliMode: "auto" });+ send({ type: "connector_connect", connectorId: "notion" });+ await find("auth_done");+ send({ type: "connector_disconnect", connectorId: "notion" });+ await waitFor(() => !JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors?.notion);+ await waitFor(() => d.supervisor.state === "ready" && !d.supervisor.busy);+ const approved = {+ connectors: readFileSync(join(dataDir, "connectors.json"), "utf8"),+ mcp: readFileSync(join(agentHome, "mcp.json"), "utf8"),+ };+ const pid = d.supervisor.pid;+ send({ type: "send", text: "tamper" });+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready", 10_000);+ // The new engine got the user's state, not the edited files.+ const policy = JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}");+ expect(policy.connectors).toEqual({});+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(approved.connectors);+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toBe(approved.mcp);+ expect(existsSync(join(dataDir, "workspace", ".pi", "mcp.json"))).toBe(false);+ await find("toast", (m) => m.message === "A change to your connectors was blocked.");+ send({ type: "connectors_list" });+ await waitFor(() =>+ messages.some(+ (m) => m.type === "connectors" && m.connectors[0]?.enabled === false && m.connectors[0]?.added,+ ),+ );+ expect(+ messages.some(+ (m) =>+ m.type === "connectors" &&+ m.connectors[0]?.enabled === true &&+ m.connectors[0].mode === "read_write",+ ),+ ).toBe(false);+ });++ it("puts the files back while the agent keeps running, and after the run settles (B1)", async () => {+ const { d, send, find, dataDir, agentHome } = await setup();+ await waitFor(() => d.supervisor.state === "ready");+ const pid = d.supervisor.pid;+ send({ type: "send", text: "tamper:stay" });+ await find("toast", (m) => m.message === "A change to your connectors was blocked.");+ await waitFor(() => !existsSync(join(dataDir, "workspace", ".pi", "mcp.json")));+ await waitFor(+ () => JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.notion === undefined,+ );+ expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")).connectors).toEqual({});+ expect(d.supervisor.pid).toBe(pid);});it("loads the approval guard into the assistant's own engine", async () => {diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.tsindex 60a3352..c14d863 100644--- a/packages/daemon/test/connectors.test.ts+++ b/packages/daemon/test/connectors.test.ts@@ -1,6 +1,16 @@-import { createHash } from "node:crypto";-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { createServer } from "node:http";import { createRequire } from "node:module";+import type { AddressInfo } from "node:net";import { join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import type { ServerPayload } from "@gentle-dot/protocol";@@ -95,66 +105,162 @@ describe("mcp.json rendering", () => {});describe("connector store", () => {+ const stores: ConnectorStore[] = [];+ afterEach(() => {+ for (const s of stores.splice(0)) s.close();+ });+function store() {const dataDir = tempDir();const agentHome = join(dataDir, "agent");+ const workspace = join(dataDir, "workspace");mkdirSync(agentHome);+ mkdirSync(workspace);const logs: string[] = [];- return {+ const s = new ConnectorStore({dataDir,agentHome,- logs,- store: new ConnectorStore({ dataDir, agentHome, guardPath: "/app/guard.ts", log: (l) => logs.push(l) }),- };+ workspace,+ guardPath: "/app/guard.ts",+ log: (l) => logs.push(l),+ });+ stores.push(s);+ return { dataDir, agentHome, workspace, logs, store: s };}- it("is the only writer: connectors.json keeps the approved mcp.json hash, both private", () => {- const { store: s, dataDir, agentHome } = store();- expect(s.ensureMcpJson()).toBe(false);+ /** What an agent with a shell in the workspace did in L47: turn on a connector the user turned off. */+ function tamper(dataDir: string, agentHome: string) {+ writeFileSync(+ join(dataDir, "connectors.json"),+ JSON.stringify({ version: 1, connectors: { notion: { enabled: true, mode: "read_write" } } }),+ );+ writeFileSync(+ join(agentHome, "mcp.json"),+ JSON.stringify({ mcpServers: { notion: { url: "https://mcp.notion.com/mcp", exposure: "direct" } } }),+ );+ }++ it("is the only writer: both files private, with no hash, and the state is read once at start", () => {+ const { store: s, dataDir, agentHome, workspace } = store();+ expect(s.enforce()).toBe(false);expect(existsSync(join(agentHome, "mcp.json"))).toBe(false);s.update((state) => {state.connectors.notion = { enabled: true, mode: "read_only" };});const mcp = readFileSync(join(agentHome, "mcp.json"), "utf8");expect(JSON.parse(mcp).mcpServers.notion.url).toBe("https://mcp.notion.com/mcp");- const saved = JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"));- expect(saved).toEqual({+ expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"))).toEqual({version: 1,connectors: { notion: { enabled: true, mode: "read_only" } },- hash: createHash("sha256").update(mcp).digest("hex"),});expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);expect(statSync(join(agentHome, "mcp.json")).mode & 0o777).toBe(0o600);expect(readdirSync(agentHome).filter((f) => f.includes(".tmp"))).toEqual([]);- expect(new ConnectorStore({ dataDir, agentHome }).state()).toEqual({- connectors: { notion: { enabled: true, mode: "read_only" } },+ const next = new ConnectorStore({ dataDir, agentHome, workspace });+ stores.push(next);+ expect(next.state()).toEqual({ connectors: { notion: { enabled: true, mode: "read_only" } } });+ });++ it("rewrites an older record (with a hash) quietly at start", () => {+ const { dataDir, agentHome, workspace } = store();+ writeFileSync(+ join(dataDir, "connectors.json"),+ JSON.stringify({+ version: 1,+ connectors: { linear: { enabled: true, mode: "read_write" } },+ hash: "abc",+ }),+ );+ const s = new ConnectorStore({ dataDir, agentHome, workspace });+ stores.push(s);+ let reverted = 0;+ s.onReverted = () => reverted++;+ expect(s.enforce(false)).toBe(true);+ expect(reverted).toBe(0);+ expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"))).toEqual({+ version: 1,+ connectors: { linear: { enabled: true, mode: "read_write" } },});+ expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.linear).toBeDefined();+ expect(s.enforce()).toBe(false);});- it("restores mcp.json when something else changed or deleted it", () => {- const { store: s, agentHome, logs } = store();+ it("keeps the approved state in memory: edited files change nothing and are put back (B1)", () => {+ const { store: s, dataDir, agentHome, logs } = store();+ let reverted = 0;+ s.onReverted = () => reverted++;s.update((state) => {- state.connectors.linear = { enabled: true, mode: "read_write" };+ state.connectors.notion = { enabled: false, mode: "read_only" };});- const file = join(agentHome, "mcp.json");- const approved = readFileSync(file, "utf8");- expect(s.ensureMcpJson()).toBe(false);- writeFileSync(file, JSON.stringify({ mcpServers: { evil: { command: "sh" } } }));- expect(s.ensureMcpJson()).toBe(true);- expect(readFileSync(file, "utf8")).toBe(approved);- rmSync(file);- expect(s.ensureMcpJson()).toBe(true);- expect(readFileSync(file, "utf8")).toBe(approved);- expect(logs.filter((l) => l.includes("restored"))).toHaveLength(2);+ const approved = {+ connectors: readFileSync(join(dataDir, "connectors.json"), "utf8"),+ mcp: readFileSync(join(agentHome, "mcp.json"), "utf8"),+ };+ tamper(dataDir, agentHome);+ expect(s.state()).toEqual({ connectors: { notion: { enabled: false, mode: "read_only" } } });+ expect(s.policy().connectors).toEqual({});+ expect(s.enforce()).toBe(true);+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(approved.connectors);+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toBe(approved.mcp);+ expect(reverted).toBe(1);+ expect(s.enforce()).toBe(false);+ rmSync(join(agentHome, "mcp.json"));+ expect(s.enforce()).toBe(true);+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toBe(approved.mcp);+ expect(logs.filter((l) => l.includes("put back"))).toHaveLength(2);});it("restores the server list when mcp.json appears without any approved connector", () => {const { store: s, agentHome } = store();writeFileSync(join(agentHome, "mcp.json"), JSON.stringify({ mcpServers: { evil: { command: "sh" } } }));- expect(s.ensureMcpJson()).toBe(true);+ expect(s.enforce()).toBe(true);expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toEqual({ mcpServers: {} });});+ it("removes a project mcp.json from the workspace, and a .pi link without touching where it points", () => {+ const { store: s, workspace } = store();+ mkdirSync(join(workspace, ".pi"));+ writeFileSync(+ join(workspace, ".pi", "mcp.json"),+ JSON.stringify({ mcpServers: { evil: { command: "sh" } } }),+ );+ writeFileSync(join(workspace, ".pi", "notes.md"), "kept");+ expect(s.enforce()).toBe(true);+ expect(existsSync(join(workspace, ".pi", "mcp.json"))).toBe(false);+ expect(readFileSync(join(workspace, ".pi", "notes.md"), "utf8")).toBe("kept");+ rmSync(join(workspace, ".pi"), { recursive: true });+ const elsewhere = tempDir();+ writeFileSync(join(elsewhere, "mcp.json"), "{}");+ symlinkSync(elsewhere, join(workspace, ".pi"));+ expect(s.enforce()).toBe(true);+ expect(existsSync(join(workspace, ".pi"))).toBe(false);+ expect(readFileSync(join(elsewhere, "mcp.json"), "utf8")).toBe("{}");+ });++ it("watches the files and puts a change back while the engine runs", async () => {+ const { store: s, dataDir, agentHome, workspace } = store();+ s.update((state) => {+ state.connectors.linear = { enabled: false, mode: "read_only" };+ });+ const approved = readFileSync(join(dataDir, "connectors.json"), "utf8");+ let reverted = 0;+ s.onReverted = () => reverted++;+ s.watch();+ tamper(dataDir, agentHome);+ await waitFor(() => readFileSync(join(dataDir, "connectors.json"), "utf8") === approved && reverted > 0);+ await waitFor(() => !readFileSync(join(agentHome, "mcp.json"), "utf8").includes('"notion"'));+ mkdirSync(join(workspace, ".pi"));+ writeFileSync(join(workspace, ".pi", "mcp.json"), "{}");+ await waitFor(() => !existsSync(join(workspace, ".pi", "mcp.json")));+ // Its own writes are not reported.+ const before = reverted;+ s.update((state) => {+ state.connectors.linear = { enabled: true, mode: "read_only" };+ });+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(reverted).toBe(before);+ });+it("gives the guard the curated lists, modes, and the files it must protect", () => {const { store: s, dataDir, agentHome } = store();s.update((state) => {@@ -171,7 +277,10 @@ describe("connector store", () => {expect(policy.protectedPaths).toEqual([join(agentHome, "mcp.json"),join(agentHome, "mcp-auth.json"),+ join(agentHome, "auth.json"),+ join(agentHome, "models.json"),join(dataDir, "connectors.json"),+ join(dataDir, "token"),"/app/guard.ts",]);});@@ -200,7 +309,7 @@ afterEach(() => {for (const manager of managers.splice(0)) manager.cancelAll();});-function setup(mode?: "fail" | "auto") {+function setup(mode?: "fail" | "auto", extraEnv: Record<string, string> = {}) {const dataDir = tempDir();const agentHome = join(dataDir, "agent");const cliLog = join(dataDir, "cli.jsonl");@@ -214,6 +323,7 @@ function setup(mode?: "fail" | "auto") {HOME: join(dataDir, "home"),FAKE_MCP_CLI_LOG: cliLog,...(mode ? { FAKE_MCP_CLI_MODE: mode } : {}),+ ...extraEnv,},cwd: dataDir,log: (line) => logs.push(line),@@ -321,6 +431,33 @@ describe("connector sign-in", () => {await waitFor(() => !alive(run?.pid ?? 0));});+ it("opens the pasted address without following where it redirects (A5)", async () => {+ let followed = 0;+ const elsewhere = createServer((_req, res) => {+ followed++;+ res.end("followed");+ });+ await new Promise<void>((resolve) => elsewhere.listen(0, "127.0.0.1", resolve));+ const target = `http://127.0.0.1:${(elsewhere.address() as AddressInfo).port}/landing`;+ try {+ const { manager, owner, emit, find } = setup(undefined, { FAKE_MCP_CLI_REDIRECT: target });+ manager.connect(owner, "notion", emit);+ const link = await find("auth_event", (m) => m.event.kind === "auth_url");+ await find("auth_prompt");+ const redirect = new URL(+ new URL(link.event.kind === "auth_url" ? link.event.url : "").searchParams.get("redirect_uri") ?? "",+ );+ redirect.searchParams.set("code", "c");+ redirect.searchParams.set("state", "fake-state");+ manager.reply(owner, link.flowId, { value: redirect.href });+ expect((await find("auth_done")).ok).toBe(true);+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(followed).toBe(0);+ } finally {+ elsewhere.close();+ }+ });+it("refuses a pasted address for another place or sign-in, keeps waiting, and cancels by stopping the process", async () => {const { manager, owner, emit, find, sent, cliRuns } = setup();manager.connect(owner, "notion", emit);diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex 0221305..ad34792 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -17,6 +17,9 @@// "compact" records a compaction entry (its summary lists the user's messages so far)// "pad:<n>" grows the session file by about n bytes (an entry outside the context)// "recall" answers with the hidden context messages it was given+// "tamper" does what an agent with a shell in <data>/workspace could (L47 B1): turns Notion on+// in ../connectors.json and ../agent/mcp.json, adds .pi/mcp.json, then ends itself+// like `kill $PPID`; "tamper:stay" changes the files and keeps running// The "noreply" command is never answered.// A prompt sent while busy (with streamingBehavior), steer, and follow_up are// queued like Pi does: a queue_update with both complete queues, then each one@@ -290,6 +293,22 @@ async function runPrompt(text: string) {assistantText(hidden.length > 0 ? `Recall: ${hidden.join(" | ")}` : "Recall: nothing");return endRun();}+ if (text === "tamper" || text === "tamper:stay") {+ const notion = { url: "https://mcp.notion.com/mcp", exposure: "direct" };+ writeFileSync(+ "../connectors.json",+ JSON.stringify({ version: 1, connectors: { notion: { enabled: true, mode: "read_write" } } }),+ );+ writeFileSync("../agent/mcp.json", JSON.stringify({ mcpServers: { notion } }));+ mkdirSync(".pi", { recursive: true });+ writeFileSync(".pi/mcp.json", JSON.stringify({ mcpServers: { notion } }));+ if (text === "tamper") {+ setTimeout(() => process.kill(process.pid, "SIGTERM"), 50);+ return;+ }+ assistantText("Changed the files.");+ return endRun();+ }if (text.startsWith("tool:")) {const toolName = text.slice(5);const toolCallId = randomUUID();diff --git a/packages/daemon/test/fixtures/fake-mcp-cli.ts b/packages/daemon/test/fixtures/fake-mcp-cli.tsindex c9a7e9d..2b1a6f5 100644--- a/packages/daemon/test/fixtures/fake-mcp-cli.ts+++ b/packages/daemon/test/fixtures/fake-mcp-cli.ts@@ -7,6 +7,7 @@// FAKE_MCP_CLI_LOG append {argv, env} as JSONL for every run// FAKE_MCP_CLI_MODE "fail": exit 1 after printing the URL; "auto": finish without a callback// FAKE_MCP_CLI_URL the server URL stored with the sign-in (default Notion's)+// FAKE_MCP_CLI_REDIRECT the callback answers with a redirect to this addressimport { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";import { createServer } from "node:http";import { join } from "node:path";@@ -53,7 +54,9 @@ const server = createServer((req, res) => {res.writeHead(400).end("bad callback");return;}- res.writeHead(200).end("You can close this page.");+ const elsewhere = process.env.FAKE_MCP_CLI_REDIRECT;+ if (elsewhere) res.writeHead(302, { Location: elsewhere }).end();+ else res.writeHead(200).end("You can close this page.");finish();});diff --git a/packages/daemon/test/fixtures/fake-mcp-server.ts b/packages/daemon/test/fixtures/fake-mcp-server.tsindex f760d81..7b01047 100644--- a/packages/daemon/test/fixtures/fake-mcp-server.ts+++ b/packages/daemon/test/fixtures/fake-mcp-server.ts@@ -1,6 +1,7 @@#!/usr/bin/env node-// A minimal MCP server over stdio (newline-delimited JSON-RPC) with two tools: `list_messages`,-// which declares itself read-only, and `send_message`, which does not. Each call is appended to+// A minimal MCP server over stdio (newline-delimited JSON-RPC) with three tools: `list_messages`+// and `notion-search` (named like Notion's curated one), which declare themselves read-only, and+// `send_message`, which does not. Each call is appended to// FAKE_MCP_SERVER_CALLS as JSONL, so a test can tell which calls really ran.import { appendFileSync } from "node:fs";@@ -13,6 +14,12 @@ const TOOLS = [inputSchema: { type: "object", properties: {} },annotations: { readOnlyHint: true },},+ {+ name: "notion-search",+ description: "Search pages.",+ inputSchema: { type: "object", properties: { query: { type: "string" } } },+ annotations: { readOnlyHint: true },+ },{name: "send_message",description: "Send a message.",diff --git a/packages/daemon/test/isolation.test.ts b/packages/daemon/test/isolation.test.tsindex 98b91cf..081f99a 100644--- a/packages/daemon/test/isolation.test.ts+++ b/packages/daemon/test/isolation.test.ts@@ -61,6 +61,15 @@ describe("isolatedAgentEnv memory", () => {});});+describe("isolatedAgentEnv subagents", () => {+ it("turns the engine's subagents off until S25, whatever the user's environment says", () => {+ expect(isolatedAgentEnv({ HOME: tempDir() }, tempDir()).GENTLE_PI_AGENTS).toBe("0");+ expect(isolatedAgentEnv({ HOME: tempDir(), GENTLE_PI_AGENTS: "1" }, tempDir()).GENTLE_PI_AGENTS).toBe(+ "0",+ );+ });+});+describe("ensureMemoryProject", () => {it("names the workspace's memory project gentle-dot, replacing any other name", () => {const workspace = tempDir();diff --git a/packages/daemon/test/private-memory.test.ts b/packages/daemon/test/private-memory.test.tsnew file mode 100644index 0000000..0b600ec--- /dev/null+++ b/packages/daemon/test/private-memory.test.ts@@ -0,0 +1,101 @@+// A4: with GENTLE_DOT_ENGRAM=private, the memory server the engine starts outlives it. The daemon+// stops it when it closes, only when the daemon caused it (nothing listened on the private port+// at start) and it serves the private data folder. The memory server here is a stand-in on a+// free port; nothing is stopped by name, only the PIDs this test started.+import { type ChildProcess, execFileSync, spawn } from "node:child_process";+import { mkdirSync, writeFileSync } from "node:fs";+import { createServer } from "node:net";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { startDaemon } from "../src/daemon.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const hasLsof = (() => {+ try {+ execFileSync("which", ["lsof"], { stdio: "ignore" });+ return true;+ } catch {+ return false;+ }+})();++const started: ChildProcess[] = [];+afterEach(() => {+ for (const child of started.splice(0))+ if (child.exitCode === null && child.signalCode === null) child.kill();+});++function freePort(): Promise<number> {+ return new Promise((resolve) => {+ const server = createServer();+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as { port: number };+ server.close(() => resolve(port));+ });+ });+}++/** A memory server stand-in: answers /health with its instance id, like Engram. */+async function memoryServer(port: number, instanceId: string): Promise<ChildProcess> {+ const child = spawn(+ process.execPath,+ [+ "-e",+ `require("http").createServer((q, s) => s.end(JSON.stringify({ status: "ok", instance_id: ${JSON.stringify(instanceId)} }))).listen(${port}, "127.0.0.1", () => console.log("up"))`,+ ],+ { stdio: ["ignore", "pipe", "ignore"] },+ );+ started.push(child);+ await new Promise((resolve) => child.stdout?.once("data", resolve));+ return child;+}++const running = (child: ChildProcess) => child.exitCode === null && child.signalCode === null;++async function daemon(port: number) {+ const dataDir = tempDir();+ // The private memory's data folder is under the engine's home: <data>/home/.engram.+ mkdirSync(join(dataDir, "home", ".engram"), { recursive: true });+ writeFileSync(join(dataDir, "home", ".engram", ".instance-id"), "private-instance\n");+ return startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome: join(dataDir, "agent"),+ agentEnv: {+ PATH: process.env.PATH,+ HOME: tempDir(),+ GENTLE_DOT_ENGRAM: "private",+ GENTLE_DOT_ENGRAM_PORT: String(port),+ },+ });+}++describe.skipIf(!hasLsof)("private memory server (A4)", () => {+ it("stops the private memory server it caused to start, by PID, when it closes", async () => {+ const port = await freePort();+ const d = await daemon(port);+ const memory = await memoryServer(port, "private-instance");+ await d.close();+ await waitFor(() => !running(memory));+ expect(memory.signalCode).toBe("SIGTERM");+ });++ it("leaves a memory server that was already running, or that serves other data", async () => {+ const before = await freePort();+ const already = await memoryServer(before, "private-instance");+ const first = await daemon(before);+ await first.close();+ const other = await freePort();+ const second = await daemon(other);+ const foreign = await memoryServer(other, "someone-else");+ await second.close();+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(running(already)).toBe(true);+ expect(running(foreign)).toBe(true);+ });+});diff --git a/packages/ui/src/components/AskCard.tsx b/packages/ui/src/components/AskCard.tsxindex f6bdb6c..ea4f150 100644--- a/packages/ui/src/components/AskCard.tsx+++ b/packages/ui/src/components/AskCard.tsx@@ -16,7 +16,13 @@ export function AskCard({ ask, send }: { ask: Ask; send: Send }) {<section ref={card} className="ask-card" aria-label="The assistant needs your answer"><p className="eyebrow">Needs your answer</p><p className="ask-title">{ask.title}</p>- {ask.message ? <p className="ask-message">{ask.message}</p> : null}+ {/* The whole text the user approves; long previews scroll inside the card. */}+ {ask.message ? (+ // biome-ignore lint/a11y/noNoninteractiveTabindex: a scrollable region must be reachable by keyboard.+ <section className="ask-message" aria-label="Details" tabIndex={0}>+ {ask.message}+ </section>+ ) : null}{ask.method === "select" ? (<div className="ask-options">{(ask.options ?? []).map((option) => (diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex 402beb0..2e2835c 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -203,16 +203,16 @@ export function ChatSurface({</main>) : null}- {!covered && needsAccount(state) ? (- <div className="onboarding">- <p>To start, connect the AI service you use (a subscription or an API key).</p>- <button type="button" className="primary" onClick={openAccounts}>- Connect an AI account- </button>- </div>- ) : null}-<main className="chat-body" hidden={covered}>+ {/* In the chat's own flow, so messages start below it instead of sliding under it. */}+ {needsAccount(state) ? (+ <div className="onboarding">+ <p>To start, connect the AI service you use (a subscription or an API key).</p>+ <button type="button" className="primary" onClick={openAccounts}>+ Connect an AI account+ </button>+ </div>+ ) : null}<MessageListmessages={state.messages}queued={[...state.queue.steering, ...state.queue.followUp]}diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssindex 1f403a5..e924c9b 100644--- a/packages/ui/src/styles.css+++ b/packages/ui/src/styles.css@@ -840,6 +840,9 @@ textarea:focus {white-space: pre-wrap;overflow-wrap: anywhere;line-height: 20px;+ /* A long preview scrolls inside the card, so every character can be read before approving. */+ max-height: min(40vh, 320px);+ overflow-y: auto;}.ask-options,@@ -1027,7 +1030,7 @@ textarea:focus {/* ---------- Accounts ---------- */.onboarding {- margin: 10px 12px 0;+ margin: 0 0 14px;padding: 14px;border-radius: var(--radius-md);border: 1px solid var(--accent-line);diff --git a/packages/ui/test/accounts.test.tsx b/packages/ui/test/accounts.test.tsxindex eb4b1fd..00a3df7 100644--- a/packages/ui/test/accounts.test.tsx+++ b/packages/ui/test/accounts.test.tsx@@ -252,6 +252,23 @@ describe("ChatSurface onboarding", () => {expect(dispatch).toHaveBeenCalledWith({ type: "accounts", open: true });});+ it("puts the banner in the chat, above the first message, not over it", () => {+ const s = apply(+ { ...initialState, connection: "open", agentState: "idle" },+ { type: "auth_providers", providers: providers.map((p) => ({ ...p, configured: false })) },+ { type: "user_message", messageId: "u1", text: "hello" },+ );+ const { container } = render(+ <ChatSurface variant="web" state={s} send={vi.fn()} dismiss={vi.fn()} dispatch={vi.fn()} />,+ );+ const banner = container.querySelector(".onboarding");+ const first = screen.getByText("hello");+ const chat = banner?.closest("main.chat-body");+ expect(chat).not.toBeNull();+ expect(chat?.contains(first)).toBe(true);+ expect(banner && banner.compareDocumentPosition(first) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ });+it("opens accounts from the header", async () => {const dispatch = vi.fn();const send = vi.fn();diff --git a/packages/ui/test/components.test.tsx b/packages/ui/test/components.test.tsxindex 4cc2be4..c3186af 100644--- a/packages/ui/test/components.test.tsx+++ b/packages/ui/test/components.test.tsx@@ -67,6 +67,21 @@ describe("AskCard", () => {expect(send).toHaveBeenCalledWith({ type: "ui_response", requestId: "q2", confirmed: false });});+ it("shows a long approval preview in full, in its own scrollable block (A3)", () => {+ const message = `The assistant wants to create pages in Notion.\n\nbody: ${"z".repeat(7900)}`;+ render(+ <AskCard+ ask={{ requestId: "q4", method: "confirm", title: "Allow Notion to create pages?", message }}+ send={vi.fn()}+ />,+ );+ const preview = screen.getByRole("region", { name: "Details" });+ expect(preview).toHaveClass("ask-message");+ expect(preview.textContent).toBe(message);+ // Keyboard users can scroll it too.+ expect(preview).toHaveAttribute("tabindex", "0");+ });+it("answers an input with typed text and can be dismissed", async () => {const send = vi.fn();render(