#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(cli): install pinned iii to private dir, fall back on PATH mismatch (#774)
Rohit Ghumare4b593e04d499
diff --git a/src/cli.ts b/src/cli.tsindex 040ad4cd..98244be0 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -34,7 +34,7 @@ import {import {buildRemovePlan,formatPlan,- localBinIii,+ legacyLocalBinIii,type ConnectManifest,type RemoveOptions,} from "./cli/remove-plan.js";@@ -347,18 +347,45 @@ function whichBinary(name: string): string | null {}}+// Private install location agentmemory manages itself. Sits under the+// agentmemory state dir (~/.agentmemory/bin) so the pinned engine stays+// isolated from a user-managed iii on PATH or in ~/.local/bin. #752: a+// fresh box with iii 0.16.1 already on PATH refused to boot because the+// hard-pin enforcer told users to overwrite their global install with+// v0.11.2. Private install resolves the conflict without touching their+// existing iii.+function agentmemoryBinDir(): string {+ if (IS_WINDOWS) {+ const userProfile = process.env["USERPROFILE"];+ if (!userProfile) return join(homedir(), ".agentmemory", "bin");+ return join(userProfile, ".agentmemory", "bin");+ }+ return join(homedir(), ".agentmemory", "bin");+}++function privateIiiPath(): string {+ return join(agentmemoryBinDir(), IS_WINDOWS ? "iii.exe" : "iii");+}+function fallbackIiiPaths(): string[] {if (IS_WINDOWS) {const userProfile = process.env["USERPROFILE"];- if (!userProfile) return [];- return [- join(userProfile, ".local", "bin", "iii.exe"),- join(userProfile, "bin", "iii.exe"),- ];+ const paths = [privateIiiPath()];+ if (userProfile) {+ paths.push(+ join(userProfile, ".local", "bin", "iii.exe"),+ join(userProfile, "bin", "iii.exe"),+ );+ }+ return paths;}const home = process.env["HOME"];- if (!home) return ["/usr/local/bin/iii"];- return [join(home, ".local", "bin", "iii"), "/usr/local/bin/iii"];+ const paths = [privateIiiPath()];+ if (home) {+ paths.push(join(home, ".local", "bin", "iii"));+ }+ paths.push("/usr/local/bin/iii");+ return paths;}function iiiBinVersion(binPath: string): string | null {@@ -375,28 +402,38 @@ function iiiBinVersion(binPath: string): string | null {}}-// Enforce hard-pin on iii-engine version. Soft-warn lets the worker boot-// against a mismatched engine and crash at runtime (state::list-not-found-// on v0.13.0+, sandbox-everything trap on v0.11.6+). Refuse to start and-// point the user at the downgrade command — same escape hatch as before-// via AGENTMEMORY_III_VERSION, which redefines IIPINNED_VERSION upstream-// (line 75) so the mismatch check passes for users who knowingly want to-// run against a different engine.-function enforceEngineVersionPin(iiiBinPath: string | null | undefined): void {- if (!iiiBinPath) return;+// Resolve a compatible iii binary for the pinned engine version.+//+// Soft-warn lets the worker boot against a mismatched engine and crash at+// runtime (state::list-not-found on v0.13.0+, sandbox-everything trap on+// v0.11.6+). Hard-pin without a fallback leaves the user stuck — they+// either downgrade their global iii (breaking other consumers) or set+// AGENTMEMORY_III_VERSION and hope it works.+//+// Instead: when the candidate iii on PATH is the wrong version, prefer+// the private install under ~/.agentmemory/bin/iii. If the private copy+// is missing or also mismatched, the caller installs the pinned version+// there before retrying. AGENTMEMORY_III_VERSION still overrides+// IIPINNED_VERSION upstream so users who knowingly want a different+// engine can opt in.+function resolveCompatibleIii(iiiBinPath: string | null | undefined): string | null {+ if (!iiiBinPath) return null;const detected = iiiBinVersion(iiiBinPath);- if (!detected || detected === IIPINNED_VERSION) return;- const asset = iiiReleaseAsset();- const downloadHint = asset- ? `curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v${IIPINNED_VERSION}/${asset} | tar -xz -C ~/.local/bin`- : `download v${IIPINNED_VERSION} from https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}`;- p.log.error(- `iii-engine on PATH is v${detected} but agentmemory v${VERSION} hard-pins v${IIPINNED_VERSION}. ` +- `Engine API drift causes runtime failures (e.g. state::list-not-found on v0.13.0). ` +- `Downgrade with: \`${downloadHint}\`. ` +- `Or set AGENTMEMORY_III_VERSION=${detected} to override at your own risk.`,- );- process.exit(1);+ if (detected && detected === IIPINNED_VERSION) return iiiBinPath;++ const privatePath = privateIiiPath();+ if (iiiBinPath !== privatePath && existsSync(privatePath)) {+ const privateVersion = iiiBinVersion(privatePath);+ if (privateVersion === IIPINNED_VERSION) {+ const reason = detected ? `v${detected} mismatches pin` : "probe failed";+ vlog(+ `iii at ${iiiBinPath} ${reason} v${IIPINNED_VERSION}; using private install at ${privatePath}.`,+ );+ return privatePath;+ }+ }++ return null;}function enginePidfilePath(): string {@@ -408,7 +445,7 @@ function engineStatePath(): string {}type EngineState =- | { kind: "native"; configPath: string; attached?: boolean }+ | { kind: "native"; configPath: string; attached?: boolean; binPath?: string }| { kind: "docker"; composeFile: string };function writeEnginePidfile(pid: number): void {@@ -687,8 +724,8 @@ async function runIiiInstaller(): Promise<{ ok: boolean; binPath: string | nullreturn { ok: false, binPath: null };}- const binDir = join(homedir(), ".local", "bin");- const binPath = join(binDir, "iii");+ const binDir = agentmemoryBinDir();+ const binPath = privateIiiPath();const installCmd = [`mkdir -p "${binDir}"`,`curl -fsSL "${releaseUrl}" | tar -xz -C "${binDir}"`,@@ -770,34 +807,56 @@ function spawnEngineBackground(}function startIiiBin(iiiBin: string, configPath: string): boolean {- enforceEngineVersionPin(iiiBin);const s = p.spinner();s.start(`Starting iii-engine: ${iiiBin}`);- writeEngineState({ kind: "native", configPath });+ writeEngineState({ kind: "native", configPath, binPath: iiiBin });spawnEngineBackground(iiiBin, ["--config", configPath], "iii-engine");s.stop("iii-engine process started");return true;}+// Find a pinned-compatible iii path from a list of candidates. Returns+// the first candidate whose --version matches the pin, OR returns the+// private install path if it exists and matches, OR null if no candidate+// is compatible. Caller (startEngine) auto-installs the pin to the+// private path when this returns null.+function pickCompatibleIii(candidates: Array<string | null | undefined>): string | null {+ for (const c of candidates) {+ if (!c) continue;+ const resolved = resolveCompatibleIii(c);+ if (resolved) return resolved;+ }+ return null;+}+async function startEngine(): Promise<boolean> {const configPath = findIiiConfig();- let iiiBin = whichBinary("iii");- vlog(`iii binary: ${iiiBin ?? "(not on PATH)"}, config: ${configPath || "(not found)"}`);-- if (iiiBin && configPath) return startIiiBin(iiiBin, configPath);-- for (const iiiPath of fallbackIiiPaths()) {- if (existsSync(iiiPath)) {- const v = iiiBinVersion(iiiPath);- vlog(`fallback iii at ${iiiPath} reports version: ${v ?? "unknown"}`);- p.log.info(`Found iii at: ${iiiPath}${v ? ` (v${v})` : ""}`);- process.env["PATH"] = `${dirname(iiiPath)}${PATH_DELIMITER}${process.env["PATH"] ?? ""}`;- iiiBin = iiiPath;- break;+ const pathIii = whichBinary("iii");+ vlog(`iii binary: ${pathIii ?? "(not on PATH)"}, config: ${configPath || "(not found)"}`);++ const fallbacks = fallbackIiiPaths().filter((p) => existsSync(p));+ for (const f of fallbacks) {+ const v = iiiBinVersion(f);+ vlog(`fallback iii at ${f} reports version: ${v ?? "unknown"}`);+ }++ let iiiBin = pickCompatibleIii([pathIii, ...fallbacks]);++ if (iiiBin && configPath) {+ if (iiiBin !== pathIii) {+ p.log.info(`Using iii at: ${iiiBin} (v${IIPINNED_VERSION})`);+ process.env["PATH"] = `${dirname(iiiBin)}${PATH_DELIMITER}${process.env["PATH"] ?? ""}`;}+ return startIiiBin(iiiBin, configPath);}- if (iiiBin && configPath) return startIiiBin(iiiBin, configPath);+ if (pathIii && !iiiBin) {+ const detected = iiiBinVersion(pathIii);+ vlog(+ `iii on PATH is v${detected ?? "unknown"}, pin is v${IIPINNED_VERSION}. ` ++ `Will install pinned engine to ${privateIiiPath()}.`,+ );+ }if (!configPath) {startupFailure = { kind: "no-engine" };@@ -822,8 +881,20 @@ async function startEngine(): Promise<boolean> {type Choice = "install" | "docker" | "manual";let choice: Choice;+ // Wrong-version iii on PATH is a configuration trap: any prompt would+ // confuse the user since they already "have iii installed". Skip the+ // prompt and auto-install pinned engine to the private location.+ const pathIiiMismatch = pathIii !== null && resolveCompatibleIii(pathIii) === null;+if (dockerOptIn && dockerBin && composeFile) {choice = "docker";+ } else if (pathIiiMismatch) {+ choice = "install";+ const detected = iiiBinVersion(pathIii!);+ p.log.info(+ `iii on PATH is v${detected ?? "unknown"} but agentmemory pins v${IIPINNED_VERSION}. ` ++ `Installing pinned engine to ~/.agentmemory/bin (leaves your existing iii untouched).`,+ );} else if (!interactive) {choice = "install";p.log.info("Non-interactive environment detected — auto-installing iii-engine.");@@ -832,7 +903,7 @@ async function startEngine(): Promise<boolean> {const options: { value: Choice; label: string; hint?: string }[] = [{value: "install",- label: `Install iii v${IIPINNED_VERSION} to ~/.local/bin (~6MB, ~5s)`,+ label: `Install iii v${IIPINNED_VERSION} to ~/.agentmemory/bin (~6MB, ~5s)`,hint: "recommended",},];@@ -932,7 +1003,7 @@ function installInstructions(): string[] {];}const linuxInstall = releaseUrl- ? ` A) curl -fsSL "${releaseUrl}" | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii`+ ? ` A) mkdir -p ~/.agentmemory/bin && curl -fsSL "${releaseUrl}" | tar -xz -C ~/.agentmemory/bin && chmod +x ~/.agentmemory/bin/iii`: ` A) Manual download: https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}`;return [`agentmemory needs iii-engine v${IIPINNED_VERSION}. Pick one:`,@@ -1059,9 +1130,34 @@ async function main() {if (await isEngineRunning()) {if (IS_VERBOSE) p.log.success("iii-engine is running");+ // Prefer the binary path persisted at launch time over whatever's on+ // PATH now. PATH lookups misfire when a global iii install gets added+ // after agentmemory started (or when the running engine was launched+ // from a path that's no longer first on PATH).+ const persisted = readEngineState();+ const persistedBin =+ persisted?.kind === "native" && persisted.binPath && existsSync(persisted.binPath)+ ? persisted.binPath+ : null;const attachedBin =- whichBinary("iii") ?? fallbackIiiPaths().find((p) => existsSync(p)) ?? null;- enforceEngineVersionPin(attachedBin);+ persistedBin ??+ whichBinary("iii") ??+ fallbackIiiPaths().find((p) => existsSync(p)) ??+ null;+ if (attachedBin) {+ const detected = iiiBinVersion(attachedBin);+ if (detected && detected !== IIPINNED_VERSION) {+ p.log.error(+ `Attached iii-engine appears to be v${detected} (from ${attachedBin}) ` ++ `but agentmemory v${VERSION} hard-pins v${IIPINNED_VERSION}. ` ++ `Engine API drift causes runtime failures (e.g. state::list-not-found on v0.13.0+). ` ++ `Stop the running engine (\`agentmemory stop --force\`) and re-run \`agentmemory\` ` ++ `to install the pinned engine into ~/.agentmemory/bin without touching ${attachedBin}. ` ++ `Or set AGENTMEMORY_III_VERSION=${detected} to override at your own risk.`,+ );+ process.exit(1);+ }+ }adoptRunningEngine();await import("./index.js");if (await waitForAgentmemoryReady(15000)) {@@ -1345,7 +1441,7 @@ function buildDoctorEffects(): DoctorEffects {return pidAlive(pid);},findIiiBinary: () => whichBinary("iii"),- localBinIiiPath: () => join(homedir(), ".local", "bin", IS_WINDOWS ? "iii.exe" : "iii"),+ localBinIiiPath: () => privateIiiPath(),iiiBinaryVersion: (binPath: string) => iiiBinVersion(binPath),viewerReachable: async (timeoutMs = 2000) => {try {@@ -2551,7 +2647,7 @@ function loadConnectManifest(home: string): ConnectManifest | null {}function probeLocalBinIiiVersion(home: string): string | null {- const path = localBinIii(home);+ const path = legacyLocalBinIii(home);if (!existsSync(path)) return null;return iiiBinVersion(path);}diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.tsindex c1dee4f4..10d95136 100644--- a/src/cli/doctor-diagnostics.ts+++ b/src/cli/doctor-diagnostics.ts@@ -157,7 +157,7 @@ export type DoctorEffects = {pidfileExists: () => boolean;/** Resolve the iii binary on PATH; return null if not found. */findIiiBinary: () => string | null;- /** Path to ~/.local/bin/iii (the location we install to). */+ /** Path to ~/.agentmemory/bin/iii (the private install location). */localBinIiiPath: () => string;/** Run `iii --version`; null if it fails. */iiiBinaryVersion: (binPath: string) => string | null;@@ -308,13 +308,14 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] {{id: "iii-on-path-not-local-bin",message:- "iii is on PATH but not in ~/.local/bin/iii (where we install).",+ "iii is on PATH but not at agentmemory's private install path.",fixPreview:- "Suggest re-installing the pinned version via the installer — won't touch your PATH.",+ "Install the pinned version to ~/.agentmemory/bin — won't touch your PATH.",moreInfo:- "agentmemory's installer writes to ~/.local/bin/iii. When a user-managed iii " +- "lives somewhere else (homebrew, cargo, $XDG_BIN) we don't auto-overwrite it. " +- "If you want our pinned build, run the installer; otherwise this is informational.",+ "agentmemory installs its pinned engine to ~/.agentmemory/bin/iii so a " ++ "user-managed iii on PATH (homebrew, cargo, manual install) stays untouched. " ++ "When agentmemory needs the pin and PATH doesn't have it, it falls back to the " ++ "private install. If neither exists, run the installer.",manualOnly: true,check: async () => {const bin = effects.findIiiBinary();@@ -330,7 +331,7 @@ export function buildDiagnostics(effects: DoctorEffects): Diagnostic[] {ok: r.ok,message:r.message ??- "Installer wrote to ~/.local/bin/iii. Your PATH wasn't modified — adjust it yourself if needed.",+ "Installer wrote to ~/.agentmemory/bin/iii. Your PATH wasn't modified.",})),},];diff --git a/src/cli/remove-plan.ts b/src/cli/remove-plan.tsindex 223d94c5..fbc64de1 100644--- a/src/cli/remove-plan.ts+++ b/src/cli/remove-plan.ts@@ -90,10 +90,27 @@ export function dataDir(home: string): string {return join(home, ".agentmemory", "data");}-export function localBinIii(home: string): string {- return join(home, ".local", "bin", "iii");+// Platform-aware binary name. Windows requires the .exe suffix or the+// existsSync probe misses the installed binary.+function iiiBinFile(): string {+ return process.platform === "win32" ? "iii.exe" : "iii";}+// Legacy install location. Older agentmemory versions wrote the pinned iii+// engine here. Kept so `agentmemory remove` can still clean up after them.+export function legacyLocalBinIii(home: string): string {+ return join(home, ".local", "bin", iiiBinFile());+}++// Current private install location. Lives under ~/.agentmemory/ so it+// stays isolated from any user-managed iii on PATH.+export function privateIiiBin(home: string): string {+ return join(home, ".agentmemory", "bin", iiiBinFile());+}++// Back-compat shim for any caller still importing the old name.+export const localBinIii = privateIiiBin;+function safeSize(path: string): number {try {return statSync(path).size;@@ -195,21 +212,39 @@ export function buildRemovePlan(}}- // ~/.local/bin/iii — only remove if it matches the version we installed.+ // Private install (~/.agentmemory/bin/iii) — agentmemory owns this path,+ // so it's always safe to remove. The version check still gates the+ // legacy ~/.local/bin/iii path which may be a user-managed install we+ // don't own.+ const privIii = privateIiiBin(home);+ if (pathExists(privIii)) {+ plan.push({+ id: "private-bin-iii",+ description: `Delete ~/.agentmemory/bin/iii (agentmemory's private install)`,+ path: privIii,+ alwaysAsk: false,+ applicable: true,+ sizeBytes: safeSize(privIii),+ });+ }++ // Legacy ~/.local/bin/iii — only remove if it matches the version we+ // installed. Older agentmemory wrote here; newer versions don't but the+ // file may still be a leftover from a previous install.// Heuristic: spawn `iii --version`; if it returns pinnedVersion, safe to// remove. Otherwise mark `alwaysAsk` so the operator confirms explicitly.- const localIii = localBinIii(home);- if (pathExists(localIii)) {+ const legacyIii = legacyLocalBinIii(home);+ if (pathExists(legacyIii)) {const matches = localBinIiiVersion === pinnedVersion;plan.push({- id: "local-bin-iii",+ id: "legacy-local-bin-iii",description: matches- ? `Delete ~/.local/bin/iii (matches pinned v${pinnedVersion})`- : `Delete ~/.local/bin/iii (version ${localBinIiiVersion ?? "unknown"} != pinned v${pinnedVersion}) — will ask`,- path: localIii,+ ? `Delete ~/.local/bin/iii (legacy install location, matches pinned v${pinnedVersion})`+ : `Delete ~/.local/bin/iii (legacy install location, version ${localBinIiiVersion ?? "unknown"} != pinned v${pinnedVersion}) — will ask`,+ path: legacyIii,alwaysAsk: !matches,applicable: true,- sizeBytes: safeSize(localIii),+ sizeBytes: safeSize(legacyIii),});}diff --git a/test/cli-remove.test.ts b/test/cli-remove.test.tsindex ac5794e1..2484d4f8 100644--- a/test/cli-remove.test.ts+++ b/test/cli-remove.test.ts@@ -115,7 +115,7 @@ describe("buildRemovePlan", () => {ctx({ localBinIiiVersion: "9.9.9" }),{ force: false, keepData: false },);- const item = plan.find((p) => p.id === "local-bin-iii")!;+ const item = plan.find((p) => p.id === "legacy-local-bin-iii")!;expect(item.applicable).toBe(true);expect(item.alwaysAsk).toBe(true);});@@ -126,7 +126,7 @@ describe("buildRemovePlan", () => {ctx({ localBinIiiVersion: "0.11.2" }),{ force: false, keepData: false },);- const item = plan.find((p) => p.id === "local-bin-iii")!;+ const item = plan.find((p) => p.id === "legacy-local-bin-iii")!;expect(item.applicable).toBe(true);expect(item.alwaysAsk).toBe(false);expect(item.description).toContain("matches pinned");@@ -134,7 +134,18 @@ describe("buildRemovePlan", () => {it("local-bin/iii absent: no plan entry created", () => {const plan = buildRemovePlan(ctx(), { force: false, keepData: false });- expect(plan.find((p) => p.id === "local-bin-iii")).toBeUndefined();+ expect(plan.find((p) => p.id === "legacy-local-bin-iii")).toBeUndefined();+ expect(plan.find((p) => p.id === "private-bin-iii")).toBeUndefined();+ });++ it("private ~/.agentmemory/bin/iii is removed without prompt", () => {+ touch(".agentmemory/bin/iii", "fakebin");+ const plan = buildRemovePlan(ctx(), { force: false, keepData: false });+ const item = plan.find((p) => p.id === "private-bin-iii")!;+ expect(item).toBeDefined();+ expect(item.applicable).toBe(true);+ expect(item.alwaysAsk).toBe(false);+ expect(item.description).toContain("private install");});});