Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(upgrade): respect pinned backend compose (#480)
Hiro-Chibab10c8c34d15b
diff --git a/ix-cli/src/cli/__tests__/upgrade-pinned-compose.test.ts b/ix-cli/src/cli/__tests__/upgrade-pinned-compose.test.tsnew file mode 100644index 00000000..ac95a145--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-pinned-compose.test.ts@@ -0,0 +1,145 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { Command } from "commander";++const mocks = vi.hoisted(() => ({+ execFileSync: vi.fn((..._args: unknown[]) => ""),+}));++vi.mock("child_process", () => ({ execFileSync: mocks.execFileSync }));+vi.mock("node:child_process", () => ({ execFileSync: mocks.execFileSync }));++const TEST_DIR = dirname(fileURLToPath(import.meta.url));+const CURRENT_CLI_VERSION = JSON.parse(+ readFileSync(join(TEST_DIR, "..", "..", "..", "package.json"), "utf-8"),+).version as string;+const BACKEND_IMAGE = "ghcr.io/ix-infrastructure/ix-memory-layer";++let home: string;+let originalIxHome: string | undefined;++beforeEach(() => {+ vi.resetModules();+ vi.clearAllMocks();++ originalIxHome = process.env.IX_HOME;+ home = mkdtempSync(join(tmpdir(), "ix-upgrade-pinned-compose-"));+ process.env.IX_HOME = home;+ mkdirSync(join(home, "backend"), { recursive: true });+ writeFileSync(join(home, ".backend-version"), "1.0.16");++ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/ix-memory-layer-dist/")) {+ return new Response(JSON.stringify({ tag_name: "v1.0.17" }), { status: 200 });+ }+ if (url.includes("/ix-compass-dist/")) {+ return new Response("", { status: 404 });+ }+ return new Response(JSON.stringify({ tag_name: `v${CURRENT_CLI_VERSION}` }), { status: 200 });+ }),+ );+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ rmSync(home, { recursive: true, force: true });+ if (originalIxHome === undefined) delete process.env.IX_HOME;+ else process.env.IX_HOME = originalIxHome;+});++async function runUpgrade(compose: string, args: string[] = []): Promise<string> {+ writeFileSync(join(home, "backend", "docker-compose.yml"), compose);++ const { registerUpgradeCommand } = await import("../commands/upgrade.js");+ const program = new Command();+ program.name("ix").exitOverride();+ registerUpgradeCommand(program);++ const output: string[] = [];+ const log = vi.spyOn(console, "log").mockImplementation((...values: unknown[]) => {+ output.push(values.join(" "));+ });+ const error = vi.spyOn(console, "error").mockImplementation((...values: unknown[]) => {+ output.push(values.join(" "));+ });+ try {+ await program.parseAsync(["upgrade", ...args], { from: "user" });+ } finally {+ log.mockRestore();+ error.mockRestore();+ }+ return output.join("\n");+}++function dockerCalls(): string[][] {+ return mocks.execFileSync.mock.calls+ .filter(([command]) => command === "docker")+ .map(([, args]) => args as string[]);+}++describe("ix upgrade with an existing backend compose", () => {+ it.each([+ ["tag", `${BACKEND_IMAGE}:1.0.16`],+ ["digest", `${BACKEND_IMAGE}@sha256:944f76887832`],+ ])("leaves a pinned %s, its version stamp, and its backend unchanged", async (_kind, image) => {+ const compose = `services:\n memory-layer:\n image: ${image}\n`;+ const output = await runUpgrade(compose);++ expect(readFileSync(join(home, "backend", "docker-compose.yml"), "utf-8")).toBe(compose);+ expect(readFileSync(join(home, ".backend-version"), "utf-8")).toBe("1.0.16");+ expect(dockerCalls()).not.toContainEqual(["pull", `${BACKEND_IMAGE}:latest`]);+ expect(dockerCalls().some(([command]) => command === "compose")).toBe(false);+ expect(output).toContain("Backend not upgraded");+ expect(output).toContain("Left the compose file and backend version stamp unchanged.");+ expect(output).not.toContain("Backend image updated to 1.0.17");+ expect(output).not.toContain("Backend restarted with latest image");+ expect(output).not.toContain("[ok] ix is up to date");+ expect(output).toContain("ix upgrade finished with the backend unchanged");+ });++ it("does not trust a current stamp left by an earlier upgrade over a pinned compose", async () => {+ writeFileSync(join(home, ".backend-version"), "1.0.17");+ const compose = `services:\n memory-layer:\n image: ${BACKEND_IMAGE}@sha256:944f76887832\n`;+ const output = await runUpgrade(compose);++ expect(readFileSync(join(home, "backend", "docker-compose.yml"), "utf-8")).toBe(compose);+ expect(readFileSync(join(home, ".backend-version"), "utf-8")).toBe("1.0.17");+ expect(dockerCalls()).not.toContainEqual(["pull", `${BACKEND_IMAGE}:latest`]);+ expect(dockerCalls().some(([command]) => command === "compose")).toBe(false);+ expect(output).toContain("Backend not upgraded");+ expect(output).not.toContain("Backend already on the latest version");+ expect(output).not.toContain("[ok] ix is up to date");+ expect(output).toContain("ix upgrade finished with the backend unchanged");+ });++ it("leaves the separate --check behavior unchanged", async () => {+ writeFileSync(join(home, ".backend-version"), "1.0.17");+ const compose = `services:\n memory-layer:\n image: ${BACKEND_IMAGE}@sha256:944f76887832\n`;+ const output = await runUpgrade(compose, ["--check"]);++ expect(output).not.toContain("Backend not upgraded");+ expect(output).toContain("Backend already on the latest version (1.0.17)");+ expect(output).toContain("[ok] ix is up to date");+ expect(dockerCalls()).toEqual([]);+ });++ it("still upgrades a compose that tracks the released latest image", async () => {+ const compose = `services:\n memory-layer:\n image: ${BACKEND_IMAGE}:latest\n`;+ const output = await runUpgrade(compose);++ expect(readFileSync(join(home, "backend", "docker-compose.yml"), "utf-8")).toBe(compose);+ expect(readFileSync(join(home, ".backend-version"), "utf-8")).toBe("1.0.17");+ expect(dockerCalls()).toContainEqual(["pull", `${BACKEND_IMAGE}:latest`]);+ expect(dockerCalls().some(([command]) => command === "compose")).toBe(true);+ expect(output).toContain("Backend image updated to 1.0.17");+ expect(output).toContain("Backend restarted with latest image");+ expect(output).toContain("[ok] ix is up to date");+ });+});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex 8f82d4cd..a85d65a2 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -480,6 +480,20 @@ export function composeTracksLatestBackend(composeText: string): boolean {});}+/**+ * Whether `ix upgrade` may manage the backend without replacing the user's+ * compose file. A missing file keeps the existing pull-only behavior. An+ * existing file is safe only when it follows the released `:latest` image;+ * unreadable files fail closed so a user-managed choice is never overwritten.+ */+function backendComposeAllowsUpgrade(composeFile: string): boolean {+ try {+ return composeTracksLatestBackend(readFileSync(composeFile, "utf-8"));+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === "ENOENT";+ }+}+/*** Record the backend release after something has pulled `:latest`.*@@ -1555,14 +1569,29 @@ export function registerUpgradeCommand(program: Command): void {// ── Backend (memory-layer) upgrade ───────────────────────────────const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);+ const backendComposeFile = join(IX_HOME, "backend", "docker-compose.yml");let backendImageChanged = false;- if (backendLatest && backendUpdateAvailable(backendLatest, backendCurrent)) {+ const backendUpgradeNeeded = !!backendLatest && backendUpdateAvailable(backendLatest, backendCurrent);+ const backendUpgradeSkipped = !opts.check && !backendComposeAllowsUpgrade(backendComposeFile);++ if (backendUpgradeNeeded) {outstanding.push(`backend ${backendCurrent === "0.0.0" ? "none" : backendCurrent} → ${backendLatest}`);console.log(`Backend update available: ${backendCurrent === "0.0.0" ? "none" : backendCurrent} → ${chalk.green(backendLatest)}`);+ }- if (!opts.check) {+ if (backendUpgradeSkipped) {+ console.log(+ chalk.yellow(+ `[!!] Backend not upgraded: ${backendComposeFile} does not track ${BACKEND_IMAGE}:latest.`+ )+ );+ console.log(chalk.dim(" Left the compose file and backend version stamp unchanged."));+ }++ if (backendUpgradeNeeded) {+ if (!opts.check && !backendUpgradeSkipped) {console.log("Pulling latest backend image...");try {execFileSync(@@ -1597,11 +1626,10 @@ export function registerUpgradeCommand(program: Command): void {timeout: 3000,});console.log("Restarting backend...");- const composeFile = join(IX_HOME, "backend", "docker-compose.yml");- if (existsSync(composeFile)) {+ if (existsSync(backendComposeFile)) {execFileSync("docker",- ["compose", "-f", composeFile, "up", "-d", "--pull", "always"],+ ["compose", "-f", backendComposeFile, "up", "-d", "--pull", "always"],{ stdio: "inherit" });console.log("[ok] Backend restarted with latest image");@@ -1610,9 +1638,9 @@ export function registerUpgradeCommand(program: Command): void {// Backend not running, that's fine}}- } else if (backendLatest) {+ } else if (backendLatest && !backendUpgradeSkipped) {console.log(`[ok] Backend already on the latest version (${backendCurrent})`);- } else {+ } else if (!backendLatest) {console.log("[--] Could not check backend version");}@@ -1620,7 +1648,7 @@ export function registerUpgradeCommand(program: Command): void {// The version stamp above only reflects what was last pulled, not what is// actually running. Inspect the live container so a stale local/dev image// is surfaced even when the stamp reads current.- if (!opts.check) {+ if (!opts.check && !backendUpgradeSkipped) {const imageStatus = checkBackendImage();if (imageStatus.kind === "local-build") {console.log(@@ -1750,8 +1778,15 @@ export function registerUpgradeCommand(program: Command): void {writeCache(latest, compassLatest ?? undefined, backendLatest ?? undefined);console.log("");+ // Two independent reasons the run may not end clean, and they cannot+ // both apply: `backendUpgradeSkipped` requires an install run, while+ // `closingStatus` only reports outstanding work under `--check`. The+ // skipped-backend case is checked first because it describes work this+ // run declined to do, which outranks work it merely found.const closing = closingStatus(opts.check, outstanding);- if (closing.upToDate) {+ if (backendUpgradeSkipped) {+ console.log("[!!] ix upgrade finished with the backend unchanged");+ } else if (closing.upToDate) {console.log("[ok] ix is up to date");} else {console.log(chalk.yellow(`[!!] Update available: ${closing.summary}`));