A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): use the user's global Engram and keep memories in project gentle-dot
Alan Buscaglia823363e3c542
diff --git a/README.md b/README.mdindex c6e9530..17f681f 100644--- a/README.md+++ b/README.md@@ -35,7 +35,9 @@ The app puts the Dot on the desktop and an item in the menu bar, and `⌥ Space`The daemon starts the agent (`gentle-shell --mode rpc`) as a child process and gives it the Gentle Dot identity. It restarts the agent if it crashes, reopening the same conversation, and translates its events into a small WebSocket protocol for the desktop and web interfaces. Conversations live in `~/.gentle-dot/sessions`; the access key is in `~/.gentle-dot/token`, and `~/.gentle-dot` is private to your user (mode 0700).-The assistant keeps to its own instance. The agent works in `~/.gentle-dot/workspace` (change it with `GENTLE_DOT_WORKSPACE` or `"workspace"` in `~/.gentle-dot/config.json`), and runs with its own home folder (`~/.gentle-dot/home`) and its own memory server (port 7438, `GENTLE_DOT_ENGRAM_PORT`), so it never writes to your own Gentle Shell, Pi, or Engram setup. It keeps `PATH` and reads your `~/.gitconfig` for your git identity.+The assistant keeps to its own instance. The agent works in `~/.gentle-dot/workspace` and runs with its own home folder (`~/.gentle-dot/home`), so it never writes to your own Gentle Shell or Pi setup. To point it at a folder of yours, set `GENTLE_DOT_WORKSPACE` or `"workspace"` in `~/.gentle-dot/config.json`: the agent is told to work there, but nothing is written into that folder for setup. It keeps `PATH` and reads your `~/.gitconfig` for your git identity.++Memory 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.## Checks@@ -48,7 +50,7 @@ pnpm e2e # Playwright against the daemon with the fake agentTests tagged `@real-agent` start the real `gentle-shell`; they are skipped when it is not installed.-To check that a first start writes nothing outside the assistant's instance (it installs the engine's companion packages, so it needs internet access, `engram`, and `lsof`):+To check that a first start writes nothing outside the assistant's instance and that memory goes to the global Engram in the project `gentle-dot` (it uses a temporary stand-in Engram, never yours; it installs the engine's companion packages, so it needs internet access, `engram`, and `lsof`):```bashGENTLE_DOT_ISOLATION_PROBE=1 npx vitest run packages/daemon/test/isolation-probe.test.tsdiff --git a/docs/design.md b/docs/design.mdindex 11af339..ccbb86f 100644--- a/docs/design.md+++ b/docs/design.md@@ -61,9 +61,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` = configured workspace (default: `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home).-- 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`, `GENTLE_SHELL_CONFIG`, and `ENGRAM_URL` 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: with its own HOME, the engine's memory plugin treats the user's Engram server as foreign, so the assistant runs its own Engram on `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), with its memory stored under `<dataDir>/home/.engram`. The user's Engram on 7437 is never touched.+- 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`.- 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).@@ -179,7 +179,7 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete- Pi sessions persist under `~/.gentle-dot/sessions`, and the daemon reopens the last active one after any restart.- After a crash, the turn that was in flight is lost. The conversation history remains, and the UI shows "I was interrupted. Continue?" with a Continue button that sends "Continue where you left off."-- The assistant's own Engram (port 7438) keeps decisions and progress across conversations; the Gentle workflow already consults it when resuming.+- The user's global Engram (project `gentle-dot`) keeps decisions and progress across conversations; the Gentle workflow already consults it when resuming.- Pi Durable is reconsidered only for unattended or scheduled work.## 8. Security (local)@@ -235,6 +235,6 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the app{ "port": 4317, "workspace": "~/Documents", "shortcut": "Alt+Space", "launchAtLogin": false }```-All keys are optional; `workspace` defaults to `<dataDir>/workspace`.+All keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`.-Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_PORT` (default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array).+Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array).diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex 3bbd809..06e2a8a 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -11,6 +11,7 @@ async function main(): Promise<void> {host: config.host,dataDir: config.dataDir,workspace: config.workspace,+ ...(config.preferredFolder ? { preferredFolder: config.preferredFolder } : {}),uiDir: config.uiDir,agentCommand: config.agentCommand,agentArgs: config.agentArgs,diff --git a/packages/daemon/src/config.ts b/packages/daemon/src/config.tsindex a5d7aab..b7e1205 100644--- a/packages/daemon/src/config.ts+++ b/packages/daemon/src/config.ts@@ -8,7 +8,10 @@ export interface DotConfig {port: number;host: string;dataDir: string;+ /** The engine's own working folder, `<dataDir>/workspace`. */workspace: string;+ /** The folder the user chose to work in, when it is not the engine's own workspace. */+ preferredFolder: string | undefined;uiDir: string;agentCommand: string;agentArgs: string[];@@ -81,19 +84,20 @@ function agentConfig(env: NodeJS.ProcessEnv, dataDir: string) {export function loadConfig(env: NodeJS.ProcessEnv = process.env): DotConfig {const dataDir = resolve(expandHome(env.GENTLE_DOT_DATA_DIR ?? "~/.gentle-dot"));const file = readFileConfig(dataDir);+ // The engine always works in its own workspace, which names its memory project; a+ // folder the user chose is passed to the engine as the place to work in.+ const workspace = join(dataDir, "workspace");+ const chosen =+ env.GENTLE_DOT_WORKSPACE ?? (typeof file.workspace === "string" ? file.workspace : undefined);+ const preferredFolder = chosen ? resolve(expandHome(chosen)) : undefined;return {port: env.GENTLE_DOT_PORT? parsePort(env.GENTLE_DOT_PORT, "GENTLE_DOT_PORT"): parsePort(file.port ?? 4317, "config.json"),host: env.GENTLE_DOT_HOST ?? "127.0.0.1",dataDir,- // The engine reads project settings from its workspace, so it is never the home folder by default.- workspace: resolve(- expandHome(- env.GENTLE_DOT_WORKSPACE ??- (typeof file.workspace === "string" ? file.workspace : join(dataDir, "workspace")),- ),- ),+ workspace,+ preferredFolder: preferredFolder === workspace ? undefined : preferredFolder,uiDir: resolve(env.GENTLE_DOT_UI_DIR ?? DEFAULT_UI_DIR),...agentConfig(env, dataDir),allowedOrigins: parseList(env.GENTLE_DOT_ALLOWED_ORIGINS, "GENTLE_DOT_ALLOWED_ORIGINS"),diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex e525d32..a8e6155 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -7,7 +7,7 @@ import { type ClientMessage, CloseCode, PROTOCOL_VERSION, parseClientMessage } fimport { type WebSocket, WebSocketServer } from "ws";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";-import { ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";+import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { AgentSupervisor } from "./supervisor.ts";import { identityArgs } from "./white-label.ts";@@ -16,7 +16,10 @@ export interface DaemonOptions {port: number;host: string;dataDir: string;+ /** The engine's working folder, owned by the assistant; it names the memory project. */workspace: string;+ /** A folder the user prefers to work in; the engine is told about it but keeps its own workspace. */+ preferredFolder?: string;/** Directory with the built web UI (`index.html`). */uiDir: string;agentCommand: string;@@ -86,6 +89,13 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const log = options.log ?? (() => {});const token = ensureToken(options.dataDir);mkdirSync(options.workspace, { recursive: true, mode: 0o700 });+ ensureMemoryProject(options.workspace);+ const folderArgs = options.preferredFolder+ ? [+ "--append-system-prompt",+ `The user's preferred working folder is ${options.preferredFolder}. Use absolute paths there unless told otherwise.`,+ ]+ : [];let agentEnv = { ...(options.agentEnv ?? process.env) };const homeArgs: string[] = [];if (options.agentHome) {@@ -97,7 +107,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const supervisor = new AgentSupervisor({command: options.agentCommand,args: [...(options.agentArgs ?? []), ...homeArgs],- extraArgs: [...identityArgs(options.dataDir), ...(options.agentExtraArgs ?? [])],+ extraArgs: [...identityArgs(options.dataDir), ...folderArgs, ...(options.agentExtraArgs ?? [])],cwd: options.workspace,dataDir: options.dataDir,env: agentEnv,diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex 04ac196..d2e4616 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -1,4 +1,4 @@-import { chmodSync, existsSync, mkdirSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";@@ -9,25 +9,43 @@ export function ensurePrivateDir(path: string): void {}/** Variables that could point the engine back at the user's own setup. */-const INHERITED_HOMES = ["PI_CODING_AGENT_DIR", "GENTLE_PI_AGENT_HOME", "GENTLE_SHELL_CONFIG", "ENGRAM_URL"];+const INHERITED_HOMES = ["PI_CODING_AGENT_DIR", "GENTLE_PI_AGENT_HOME", "GENTLE_SHELL_CONFIG"];++/** The memory project every memory the assistant saves or searches belongs to. */+export const MEMORY_PROJECT = "gentle-dot";++/** The memory server port of the private memory (`GENTLE_DOT_ENGRAM=private`). */+export const PRIVATE_ENGRAM_PORT = "7438";/**- * The assistant's own memory server port. Engram ties a server to the HOME- * that started it and refuses one started from another HOME, so the user's- * server (port 7437) can be used by neither side once the homes differ.+ * Names the memory project of `workspace` through Engram's per-folder setting+ * (`.engram/config.json`), which Engram reads before any other detection.*/-export const ASSISTANT_ENGRAM_PORT = "7438";+export function ensureMemoryProject(workspace: string): void {+ ensurePrivateDir(join(workspace, ".engram"));+ writeFileSync(+ join(workspace, ".engram", "config.json"),+ `${JSON.stringify({ project_name: MEMORY_PROJECT })}\n`,+ );+}/*** The engine's environment: its own HOME (`<dataDir>/home`, mode 0700) with* the XDG folders under it, because parts of the engine write to fixed places- * under the home folder, and its own memory server port. PATH is kept, and so- * is the user's git identity, through `GIT_CONFIG_GLOBAL` pointing at their- * real `~/.gitconfig`. `GENTLE_DOT_ENGRAM_PORT` overrides the memory port.+ * under the home folder. PATH is kept, and so is the user's git identity,+ * through `GIT_CONFIG_GLOBAL` pointing at their real `~/.gitconfig`.+ *+ * Memory is the user's global Engram: Engram ties a server to its data folder+ * (by default under HOME), so `ENGRAM_DATA_DIR` points at the user's real one+ * (`GENTLE_DOT_ENGRAM_DATA_DIR` overrides it) and the memory plugin accepts the+ * 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).*/export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeJS.ProcessEnv {const home = join(dataDir, "home");ensurePrivateDir(home);+ const realHome = base.HOME || homedir();const env: NodeJS.ProcessEnv = {...base,HOME: home,@@ -35,10 +53,17 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeXDG_DATA_HOME: join(home, ".local", "share"),XDG_CACHE_HOME: join(home, ".cache"),XDG_STATE_HOME: join(home, ".local", "state"),- ENGRAM_PORT: base.GENTLE_DOT_ENGRAM_PORT || ASSISTANT_ENGRAM_PORT,};for (const key of INHERITED_HOMES) delete env[key];- const gitConfig = join(base.HOME || homedir(), ".gitconfig");+ if (base.GENTLE_DOT_ENGRAM === "private") {+ env.ENGRAM_PORT = base.GENTLE_DOT_ENGRAM_PORT || PRIVATE_ENGRAM_PORT;+ delete env.ENGRAM_URL;+ delete env.ENGRAM_DATA_DIR;+ } else {+ env.ENGRAM_DATA_DIR =+ base.GENTLE_DOT_ENGRAM_DATA_DIR || base.ENGRAM_DATA_DIR || join(realHome, ".engram");+ }+ const gitConfig = join(realHome, ".gitconfig");if (!base.GIT_CONFIG_GLOBAL && existsSync(gitConfig)) env.GIT_CONFIG_GLOBAL = gitConfig;return env;}diff --git a/packages/daemon/test/config.test.ts b/packages/daemon/test/config.test.tsindex 8867bb4..91a0a9e 100644--- a/packages/daemon/test/config.test.ts+++ b/packages/daemon/test/config.test.ts@@ -17,6 +17,7 @@ describe("loadConfig", () => {// Never the user's home: the engine reads project settings from its workspace.workspace: join(dataDir, "workspace"),});+ expect(config.preferredFolder).toBeUndefined();expect(config.agentArgs).toHaveLength(1);expect(config.agentArgs[0]).toMatch(/node_modules\/gentle-pi\/bin\/gentle-shell\.mjs$/);expect(existsSync(config.agentArgs[0] ?? "")).toBe(true);@@ -45,11 +46,26 @@ describe("loadConfig", () => {it("reads config.json and lets environment variables win", () => {const dataDir = tempDir();- writeFileSync(join(dataDir, "config.json"), JSON.stringify({ port: 5000, workspace: dataDir }));- expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir })).toMatchObject({ port: 5000, workspace: dataDir });+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({ port: 5000, workspace: "/projects" }));+ expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir })).toMatchObject({+ port: 5000,+ preferredFolder: "/projects",+ });expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_PORT: "6000" }).port).toBe(6000);});+ it("keeps the engine in its own workspace and treats a custom one as the user's preferred folder", () => {+ const dataDir = tempDir();+ const config = loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_WORKSPACE: "/work/repo" });+ // The workspace holds the memory project setting, so the engine always works there.+ expect(config).toMatchObject({ workspace: join(dataDir, "workspace"), preferredFolder: "/work/repo" });+ const same = loadConfig({+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_WORKSPACE: join(dataDir, "workspace"),+ });+ expect(same.preferredFolder).toBeUndefined();+ });+it("rejects an invalid port and a malformed argument list", () => {const dataDir = tempDir();expect(() => loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_PORT: "abc" })).toThrow(diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex ff60d98..355382c 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -19,6 +19,7 @@// FAKE_AGENT_ARGS_FILE write argv as JSON to this file// FAKE_AGENT_BRANDING emit branded startup UI records// FAKE_AGENT_ENV_FILE write selected environment variables as JSON to this file+// FAKE_AGENT_CWD_FILE write the working directory to this file// FAKE_AGENT_COMMANDS_FILE append every model command (set_model, set_thinking_level) as JSONL// FAKE_AGENT_NO_MODEL refuse every prompt, like an engine with no signed-in account// FAKE_AGENT_DROP_QUEUE settle without taking or reporting queued messages@@ -52,6 +53,7 @@ let thinkingLevel = "medium";const argv = process.argv.slice(2);if (process.env.FAKE_AGENT_ARGS_FILE) writeFileSync(process.env.FAKE_AGENT_ARGS_FILE, JSON.stringify(argv));+if (process.env.FAKE_AGENT_CWD_FILE) writeFileSync(process.env.FAKE_AGENT_CWD_FILE, process.cwd());if (process.env.FAKE_AGENT_ENV_FILE) {writeFileSync(process.env.FAKE_AGENT_ENV_FILE,@@ -70,6 +72,7 @@ if (process.env.FAKE_AGENT_ENV_FILE) {"GENTLE_SHELL_CONFIG","ENGRAM_PORT","ENGRAM_URL",+ "ENGRAM_DATA_DIR",].map((key) => [key, process.env[key]]),),),diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.tsindex eebcbed..9855783 100644--- a/packages/daemon/test/gateway.test.ts+++ b/packages/daemon/test/gateway.test.ts@@ -459,7 +459,7 @@ describe("own instance", () => {expect(env.GENTLE_PI_CONFIG_HOME).toBe(join(dataDir, "gentle-ai"));});- it("gives the agent its own HOME, XDG folders, and memory server, keeping PATH and the user's git identity", async () => {+ it("gives the agent its own HOME and XDG folders, keeping PATH, the user's git identity, and the user's Engram", async () => {const scratch = tempDir();const realHome = join(scratch, "user");mkdirSync(realHome);@@ -500,8 +500,9 @@ describe("own instance", () => {XDG_STATE_HOME: join(home, ".local", "state"),GIT_CONFIG_GLOBAL: join(realHome, ".gitconfig"),PATH: process.env.PATH,- // Engram ties a memory server to the HOME that started it, so the assistant runs its own.- ENGRAM_PORT: "7438",+ // The user's global Engram: its data dir, so the memory plugin accepts the user's server.+ ENGRAM_DATA_DIR: join(realHome, ".engram"),+ ENGRAM_URL: "http://127.0.0.1:7437",});expect(statSync(home).mode & 0o777).toBe(0o700);expect(existsSync(join(dataDir, "workspace"))).toBe(true);diff --git a/packages/daemon/test/isolation-probe.test.ts b/packages/daemon/test/isolation-probe.test.tsindex b88a44b..cc89e90 100644--- a/packages/daemon/test/isolation-probe.test.ts+++ b/packages/daemon/test/isolation-probe.test.ts@@ -1,19 +1,21 @@// @real-agent isolation probe: starts the daemon with the bundled engine for the// first time under a seeded temporary HOME and checks that HOME is byte-identical-// afterwards, and that the engine's memory server belongs to the assistant's own-// home. Opt-in (it installs the engine's companion packages and needs internet-// access; it needs `engram` and `lsof` on PATH):+// afterwards, and that the engine's memory uses the user's global Engram in the+// project gentle-dot. The "global" Engram is a stand-in on a free port with a+// temporary data folder, which the engine's memory plugin starts itself, so the+// user's real one is never used. Opt-in (it installs the engine's companion+// packages and needs internet access; it needs `engram` and `lsof` on PATH):// GENTLE_DOT_ISOLATION_PROBE=1 npx vitest run packages/daemon/test/isolation-probe.test.ts-import { execFileSync, spawn } from "node:child_process";+import { type ChildProcess, execFileSync, spawn } from "node:child_process";import { createHash } from "node:crypto";import { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { createServer } from "node:net";import { join, relative } from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { tempDir, waitFor } from "./helpers.ts";const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));-const ENGRAM_PORT = "17438";const enabled = process.env.GENTLE_DOT_ISOLATION_PROBE === "1";/** One hash over every path, type, mode, and file content under `root` (symlinks are not followed). */@@ -47,10 +49,61 @@ function seed(home: string): void {}}+function freePort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = createServer();+ server.on("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as { port: number };+ server.close(() => resolve(port));+ });+ });+}++async function json<T>(url: string, init?: RequestInit): Promise<T> {+ const response = await fetch(url, init);+ if (!response.ok) throw new Error(`${url}: ${response.status} ${await response.text()}`);+ return (await response.json()) as T;+}++function collect(child: ChildProcess): () => string {+ let output = "";+ child.stdout?.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ child.stderr?.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ return () => output;+}++/** The PID listening on `port`, if any. */+function listener(port: string): number | undefined {+ try {+ const pid = execFileSync("lsof", ["-t", `-iTCP:${port}`, "-sTCP:LISTEN"])+ .toString()+ .trim();+ return /^\d+$/.test(pid) ? Number(pid) : undefined;+ } catch {+ return undefined;+ }+}+describe.skipIf(!enabled)("@real-agent isolation probe", () => {- it("leaves the user's HOME untouched on a first start", { timeout: 300_000 }, async () => {+ it("leaves HOME untouched and keeps memory in the global Engram, project gentle-dot", {+ timeout: 300_000,+ }, async () => {const home = tempDir();const dataDir = join(tempDir(), "data");+ // The stand-in for the user's global Engram: a temporary data folder and a free port.+ const globalData = join(tempDir(), "engram");+ const engramPort = String(await freePort());+ const engramUrl = `http://127.0.0.1:${engramPort}`;+ const globalId = execFileSync("engram", ["instance-id"], {+ env: { PATH: process.env.PATH, HOME: tempDir(), ENGRAM_DATA_DIR: globalData },+ })+ .toString()+ .trim();seed(home);const before = hashTree(home);const child = spawn(process.execPath, [CLI], {@@ -63,49 +116,75 @@ describe.skipIf(!enabled)("@real-agent isolation probe", () => {XDG_STATE_HOME: join(home, ".local", "state"),GENTLE_DOT_DATA_DIR: dataDir,GENTLE_DOT_PORT: "0",- GENTLE_DOT_ENGRAM_PORT: ENGRAM_PORT,+ GENTLE_DOT_ENGRAM_DATA_DIR: globalData,+ ENGRAM_PORT: engramPort,},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 output = collect(child);const exited = new Promise<number | null>((resolve) => child.on("close", resolve));- await waitFor(() => /Gentle Dot is running|failed to start/.test(output), 240_000);- const port = /127\.0\.0\.1:(\d+)/.exec(output)?.[1];- const health = (await (await fetch(`http://127.0.0.1:${port}/health`)).json()) as { agentState: string };- // The engine starts the assistant's own memory server when it loads.let memory: { instance_id?: string } | undefined;- for (let i = 0; i < 60 && !memory; i++) {- memory = await fetch(`http://127.0.0.1:${ENGRAM_PORT}/health`).then(- (r) => r.json() as Promise<{ instance_id?: string }>,- () => new Promise<undefined>((resolve) => setTimeout(resolve, 1000)),+ try {+ await waitFor(() => /Gentle Dot is running|failed to start/.test(output()), 240_000);+ const port = /127\.0\.0\.1:(\d+)/.exec(output())?.[1];+ const health = await json<{ agentState: string }>(`http://127.0.0.1:${port}/health`);+ // No memory server was running: the engine's memory plugin starts the global one,+ // with the user's data folder, on the user's port.+ for (let i = 0; i < 60 && !memory; i++) {+ memory = await json<{ instance_id?: string }>(`${engramUrl}/health`).catch(+ () => new Promise<undefined>((resolve) => setTimeout(resolve, 1000)),+ );+ }+ // The engine's memory plugin resolves its project with this same call on its workspace.+ const workspace = join(dataDir, "workspace");+ const current = await json<{ project?: string; project_source?: string }>(+ `${engramUrl}/project/current?cwd=${encodeURIComponent(workspace)}`,);+ // What the plugin's mem_save sends for a memory with no explicit project.+ const session = `gentle-dot-probe-${Date.now()}`;+ await json(`${engramUrl}/sessions`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ id: session, project: current.project, directory: workspace }),+ });+ const saved = await json<{ id: number }>(`${engramUrl}/observations`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: session,+ title: "Probe memory",+ content: "Saved by the isolation probe",+ type: "manual",+ project: current.project,+ scope: "project",+ }),+ });+ const observation = await json<{ project?: string }>(`${engramUrl}/observations/${saved.id}`);+ child.kill("SIGTERM");+ await exited;+ const after = hashTree(home);+ console.log(+ `HOME: ${home}\nagent state: ${health.agentState}\nHOME before: ${before}\nHOME after: ${after}\n` ++ `stand-in Engram: ${engramUrl}, data ${globalData}\n` ++ `memory server instance: ${memory?.instance_id}\nglobal data instance: ${globalId}\n` ++ `project for the workspace: ${current.project} (${current.project_source})\n` ++ `observation ${saved.id} project: ${observation.project}`,+ );+ console.log(output().slice(0, 4000));+ expect(health.agentState).toBe("idle");+ expect(memory?.instance_id).toBe(globalId);+ expect(readdirSync(join(dataDir, "home")).includes(".engram")).toBe(false);+ expect(current).toMatchObject({ project: "gentle-dot", project_source: "config" });+ expect(observation.project).toBe("gentle-dot");+ expect(output()).not.toContain("#token=");+ expect(after).toBe(before);+ } finally {+ if (child.exitCode === null) child.kill("SIGTERM");+ // Stop the stand-in only after checking it is the one on the probe's own data folder.+ const pid = listener(engramPort);+ const id = await json<{ instance_id?: string }>(`${engramUrl}/health`).catch(() => undefined);+ if (pid && id?.instance_id === globalId) process.kill(pid, "SIGTERM");+ console.log(`stand-in Engram pid ${pid} stopped: ${Boolean(pid && id?.instance_id === globalId)}`);}- const ownId = execFileSync("engram", ["instance-id"], {- env: { PATH: process.env.PATH, HOME: join(dataDir, "home") },- })- .toString()- .trim();- child.kill("SIGTERM");- await exited;- const memoryPid = execFileSync("lsof", ["-t", `-iTCP:${ENGRAM_PORT}`, "-sTCP:LISTEN"])- .toString()- .trim();- if (/^\d+$/.test(memoryPid)) process.kill(Number(memoryPid), "SIGTERM");- const after = hashTree(home);- console.log(- `HOME: ${home}\nagent state: ${health.agentState}\nHOME before: ${before}\nHOME after: ${after}`,- );- console.log(`memory server: ${memory?.instance_id}\nassistant home instance: ${ownId}`);- console.log(output.slice(0, 4000));- expect(health.agentState).toBe("idle");- expect(memory?.instance_id).toBe(ownId);- expect(output).not.toContain("#token=");- expect(after).toBe(before);});});diff --git a/packages/daemon/test/isolation.test.ts b/packages/daemon/test/isolation.test.tsnew file mode 100644index 0000000..98b91cf--- /dev/null+++ b/packages/daemon/test/isolation.test.ts@@ -0,0 +1,149 @@+import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import {+ ensureMemoryProject,+ isolatedAgentEnv,+ MEMORY_PROJECT,+ PRIVATE_ENGRAM_PORT,+} from "../src/isolation.ts";+import { FAKE_AGENT, tempDir } from "./helpers.ts";++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++describe("isolatedAgentEnv memory", () => {+ it("points the engine's memory at the user's global Engram data and server", () => {+ const realHome = tempDir();+ const env = isolatedAgentEnv({ PATH: "/bin", HOME: realHome }, tempDir());+ expect(env.ENGRAM_DATA_DIR).toBe(join(realHome, ".engram"));+ // The default server (7437) unless the user configured another one.+ expect(env.ENGRAM_PORT).toBeUndefined();+ expect(env.ENGRAM_URL).toBeUndefined();+ });++ it("keeps the user's own Engram settings and honors GENTLE_DOT_ENGRAM_DATA_DIR", () => {+ const realHome = tempDir();+ const base = {+ HOME: realHome,+ ENGRAM_DATA_DIR: "/srv/engram",+ ENGRAM_PORT: "7500",+ ENGRAM_URL: "http://127.0.0.1:7500",+ };+ expect(isolatedAgentEnv(base, tempDir())).toMatchObject({+ ENGRAM_DATA_DIR: "/srv/engram",+ ENGRAM_PORT: "7500",+ ENGRAM_URL: "http://127.0.0.1:7500",+ });+ const env = isolatedAgentEnv({ ...base, GENTLE_DOT_ENGRAM_DATA_DIR: "/data/engram" }, tempDir());+ expect(env.ENGRAM_DATA_DIR).toBe("/data/engram");+ });++ it("runs a private memory on its own port with GENTLE_DOT_ENGRAM=private", () => {+ const dataDir = tempDir();+ const base = {+ HOME: tempDir(),+ GENTLE_DOT_ENGRAM: "private",+ ENGRAM_DATA_DIR: "/srv/engram",+ ENGRAM_URL: "http://127.0.0.1:7437",+ ENGRAM_PORT: "7437",+ };+ const env = isolatedAgentEnv(base, dataDir);+ expect(env.ENGRAM_PORT).toBe(PRIVATE_ENGRAM_PORT);+ expect(PRIVATE_ENGRAM_PORT).toBe("7438");+ // Engram then keeps its data under the engine's own home.+ expect(env.ENGRAM_DATA_DIR).toBeUndefined();+ expect(env.ENGRAM_URL).toBeUndefined();+ expect(isolatedAgentEnv({ ...base, GENTLE_DOT_ENGRAM_PORT: "17438" }, dataDir).ENGRAM_PORT).toBe("17438");+ });+});++describe("ensureMemoryProject", () => {+ it("names the workspace's memory project gentle-dot, replacing any other name", () => {+ const workspace = tempDir();+ const file = join(workspace, ".engram", "config.json");+ ensureMemoryProject(workspace);+ expect(MEMORY_PROJECT).toBe("gentle-dot");+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ project_name: "gentle-dot" });+ writeFileSync(file, '{ "project_name": "other" }');+ ensureMemoryProject(workspace);+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ project_name: "gentle-dot" });+ });+});++describe("engine memory and folders", () => {+ async function start(options: { preferredFolder?: string; env?: NodeJS.ProcessEnv } = {}) {+ const scratch = tempDir();+ const dataDir = tempDir();+ const realHome = join(scratch, "user");+ mkdirSync(realHome);+ const files = {+ env: join(scratch, "env.json"),+ args: join(scratch, "argv.json"),+ cwd: join(scratch, "cwd.txt"),+ };+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ ...(options.preferredFolder ? { preferredFolder: options.preferredFolder } : {}),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome: join(dataDir, "agent"),+ agentEnv: {+ PATH: process.env.PATH,+ HOME: realHome,+ ...options.env,+ FAKE_AGENT_ENV_FILE: files.env,+ FAKE_AGENT_ARGS_FILE: files.args,+ FAKE_AGENT_CWD_FILE: files.cwd,+ },+ });+ daemons.push(d);+ return {+ dataDir,+ realHome,+ env: JSON.parse(readFileSync(files.env, "utf8")) as Record<string, string | undefined>,+ argv: JSON.parse(readFileSync(files.args, "utf8")) as string[],+ cwd: readFileSync(files.cwd, "utf8"),+ };+ }++ it("uses the global Engram and the gentle-dot project from the assistant's own workspace", async () => {+ const { dataDir, realHome, env, argv, cwd } = await start();+ const workspace = join(dataDir, "workspace");+ expect(env.ENGRAM_DATA_DIR).toBe(join(realHome, ".engram"));+ expect(env.ENGRAM_PORT).toBeUndefined();+ expect(env.HOME).toBe(join(dataDir, "home"));+ expect(cwd).toBe(realpathSync(workspace));+ expect(JSON.parse(readFileSync(join(workspace, ".engram", "config.json"), "utf8"))).toEqual({+ project_name: "gentle-dot",+ });+ expect(argv.join("\n")).not.toContain("preferred working folder");+ // Nothing is written to the user's Engram data by the daemon itself.+ expect(existsSync(join(realHome, ".engram"))).toBe(false);+ });++ it("keeps the private memory opt-out", async () => {+ const { env } = await start({ env: { GENTLE_DOT_ENGRAM: "private" } });+ expect(env.ENGRAM_PORT).toBe("7438");+ expect(env.ENGRAM_DATA_DIR).toBeUndefined();+ });++ it("tells the engine about a custom folder without working or writing in it", async () => {+ const folder = tempDir();+ const { dataDir, argv, cwd } = await start({ preferredFolder: folder });+ expect(cwd).toBe(realpathSync(join(dataDir, "workspace")));+ const prompts = argv.flatMap((arg, i) => (argv[i - 1] === "--append-system-prompt" ? [arg] : []));+ expect(prompts).toHaveLength(2);+ expect(prompts[1]).toBe(+ `The user's preferred working folder is ${folder}. Use absolute paths there unless told otherwise.`,+ );+ expect(readdirSync(folder)).toEqual([]);+ });+});