Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(upgrade): take the backend's word for which release is running (#467)

Joseph Mikhail7bd7276c5ab9
diff --git a/ix-cli/src/cli/__tests__/backend-release-report.test.ts b/ix-cli/src/cli/__tests__/backend-release-report.test.ts
new file mode 100644
index 00000000..e2967af9
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/backend-release-report.test.ts
@@ -0,0 +1,583 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import type { IxClient } from "../../client/api.js";
+import { isNewer } from "../commands/upgrade.js";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+
+/**
+ * `.backend-version` used to be a record of what the CLI last INSTALLED, which
+ * is the same thing as what is RUNNING only while nothing else moves the image.
+ * Pull through docker compose and the file names an older release than the
+ * container, so "Backend update available" fires on every command for ever.
+ *
+ * Ix#466 fixed the paths that run our code by recording at the pull.
+ * Ix-memory#157 makes the container report the release it was built as, so the
+ * remaining paths can be fixed by asking it. This is that consumer.
+ */
+describe("recordBackendRelease", () => {
+ let home: string;
+ let priorHome: string | undefined;
+
+ beforeEach(() => {
+ priorHome = process.env.IX_HOME;
+ home = mkdtempSync(join(tmpdir(), "ix-release-report-"));
+ process.env.IX_HOME = home;
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.resetModules();
+ if (priorHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = priorHome;
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ /** Re-imported so IX_HOME above is the one the module resolves the stamp from. */
+ const load = () => import("../backend-version.js");
+ const stamp = () => join(home, ".backend-version");
+ const tracked = () => (existsSync(stamp()) ? readFileSync(stamp(), "utf-8") : null);
+
+ /** The newest release the CLI knows about, from its own version cache. */
+ const FEED = "1.0.16";
+
+ it("writes what the backend reports", async () => {
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("1.0.16", FEED, isNewer)).toBe(true);
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("corrects a stamp that is BEHIND the running container", async () => {
+ // The reported bug: pulled a newer image outside the CLI, so the file names
+ // the release that was installed and the notice nags for ever.
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ recordBackendRelease("1.0.16", FEED, isNewer);
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("corrects a stamp that is AHEAD of the running container", async () => {
+ // The direction no local inspection can fix, and the dangerous one: an ahead
+ // stamp silences the notice through the next release the user should have
+ // been told about.
+ writeFileSync(stamp(), "1.0.17");
+ const { recordBackendRelease } = await load();
+ recordBackendRelease("1.0.16", FEED, isNewer);
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("REFUSES a container claiming to be newer than any published release", async () => {
+ // The whole reason this value is bounded. A typo in a compose override, or a
+ // tampered image, reporting 99.0.0 would otherwise be written straight in —
+ // after which backendUpdateAvailable is false for ever and `ix upgrade`
+ // reports "already on the latest version" without ever pulling, so a
+ // security release can never reach that machine.
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("99.0.0", FEED, isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("still repairs an ahead stamp when no release is known yet", async () => {
+ // With no cache there is no ceiling, so only corrections that do not move
+ // the stamp FORWARD are taken. That still fixes the dangerous direction and
+ // defers the rest until checkForUpdate populates the cache.
+ writeFileSync(stamp(), "1.0.17");
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("1.0.16", null, isNewer)).toBe(true);
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("will not move the stamp forward when no release is known yet", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("1.0.16", null, isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("ignores a corrupt ceiling rather than trusting it", async () => {
+ // readCache only checks backendLatest is a string. A garbage ceiling must
+ // fall back to the no-ceiling rule, not admit anything.
+ //
+ // "99999" and not "not-a-version": splitVersion parses the latter to major
+ // 0, so isNewer("99.0.0", "not-a-version") is true with or WITHOUT the
+ // shape check and the test passed for the wrong reason. A garbage ceiling
+ // that parses to a large major is the one that needs the guard.
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("99.0.0", "99999", isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("trims before matching, so a value with a trailing newline still lands", async () => {
+ // JS `$` does not match before a trailing newline. A value from an
+ // --env-file or a ConfigMap carries one, and without the trim the whole
+ // feature no-ops with nothing to see. getTrackedVersion already trims on
+ // the way out, so the two halves have to agree.
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("1.0.16\n", FEED, isNewer)).toBe(true);
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("writes nothing when the backend does not report a release", async () => {
+ // Every backend older than Ix-memory#157, and every image not built by the
+ // release pipeline. Absent must leave whatever was tracked alone.
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ // 1016 and {} are what a backend can actually send: HealthResponse types
+ // the field, but nothing validates the JSON at runtime.
+ for (const nothing of [undefined, null, "", " ", 1016 as any, {} as any]) {
+ expect(recordBackendRelease(nothing, FEED, isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ }
+ });
+
+ it("refuses a value that is not version-shaped, or is absurdly long", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { recordBackendRelease } = await load();
+ for (const junk of ["latest", "not a version", "../../evil", "9.9.9/../../evil"]) {
+ expect(recordBackendRelease(junk, FEED, isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ }
+ // Version-shaped the whole way, rejected only by length — so deleting the
+ // bound is caught rather than being masked by the shape test.
+ expect(recordBackendRelease("1.0.0-" + "a".repeat(100), "99.0.0", isNewer)).toBe(false);
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("accepts a release carrying a pre-release and build metadata", async () => {
+ // The shape that once broke `ix upgrade`; VERSION_RE admits it deliberately
+ // and the backend validates against the same pattern.
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("0.9.0-rc.1+abc1234", "0.9.0-rc.1+abc1234", isNewer)).toBe(true);
+ expect(tracked()).toBe("0.9.0-rc.1+abc1234");
+ });
+
+ it("does not rewrite a stamp that already agrees", async () => {
+ // Runs on every `ix status` / `ix map`. Asserted on the MTIME, not the
+ // contents: rewriting the same string leaves the contents identical, so a
+ // contents check passes whether or not the write happened.
+ writeFileSync(stamp(), "1.0.16");
+ const pinned = new Date("2020-01-02T03:04:05Z");
+ utimesSync(stamp(), pinned, pinned);
+ const before = statSync(stamp()).mtimeMs;
+
+ const { recordBackendRelease } = await load();
+ expect(recordBackendRelease("1.0.16", FEED, isNewer)).toBe(false);
+ expect(statSync(stamp()).mtimeMs).toBe(before);
+
+ // ...and the control: a different version DOES rewrite it.
+ recordBackendRelease("1.0.15", FEED, isNewer);
+ expect(statSync(stamp()).mtimeMs).not.toBe(before);
+ });
+
+ it("never throws when the write fails", async () => {
+ // Attached to commands the user actually ran — `ix status` must not fail
+ // because IX_HOME is read-only.
+ mkdirSync(stamp(), { recursive: true }); // a directory where the file goes
+ const { recordBackendRelease } = await load();
+ expect(() => recordBackendRelease("1.0.16", FEED, isNewer)).not.toThrow();
+ });
+});
+
+/**
+ * The ceiling comes from the BACKEND release feed, not the CLI's own.
+ *
+ * One word apart, and the two are different version series — so taking `latest`
+ * would make the ceiling the CLI's version (0.9.x), refuse every legitimate
+ * container report for ever, and silently reinstate the bug this exists to fix.
+ */
+describe("backendCeiling", () => {
+ let home: string;
+ let priorHome: string | undefined;
+
+ beforeEach(() => {
+ priorHome = process.env.IX_HOME;
+ home = mkdtempSync(join(tmpdir(), "ix-ceiling-"));
+ process.env.IX_HOME = home;
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.resetModules();
+ if (priorHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = priorHome;
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ it("reads the backend release, not the CLI release", async () => {
+ writeFileSync(
+ join(home, ".version-check.json"),
+ // Deliberately different series, the way they are in reality.
+ JSON.stringify({ latest: "0.9.3", backendLatest: "1.0.16", checkedAt: Date.now() }),
+ );
+ const { backendCeiling } = await import("../commands/upgrade.js");
+ expect(backendCeiling()).toBe("1.0.16");
+ });
+
+ it("is null when nothing is cached yet", async () => {
+ const { backendCeiling } = await import("../commands/upgrade.js");
+ expect(backendCeiling()).toBeNull();
+ });
+});
+
+/**
+ * The wiring, not the helpers. Every other test here calls recordBackendRelease
+ * or isLocalEndpoint directly with hand-built arguments — so gutting the one
+ * line in fetchBackendHealth that connects them left the whole suite green.
+ */
+describe("fetchBackendHealth records what it read", () => {
+ let home: string;
+ let priorHome: string | undefined;
+
+ beforeEach(() => {
+ priorHome = process.env.IX_HOME;
+ home = mkdtempSync(join(tmpdir(), "ix-fetch-health-"));
+ process.env.IX_HOME = home;
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.resetModules();
+ if (priorHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = priorHome;
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ const stamp = () => join(home, ".backend-version");
+ const tracked = () => (existsSync(stamp()) ? readFileSync(stamp(), "utf-8") : null);
+
+ /** Only what fetchBackendHealth touches: the endpoint and health(). */
+ const fakeClient = (endpoint: string, health: unknown) =>
+ ({ endpoint, health: async () => health }) as unknown as IxClient;
+
+ it("records the release for a local backend", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { fetchBackendHealth } = await import("../backend-version.js");
+ const got = await fetchBackendHealth(
+ fakeClient("http://localhost:8090", { status: "ok", release_version: "1.0.16" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(got).toMatchObject({ status: "ok" }); // still returns the response
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("applies the ceiling through readBackendHealth, the path commands take", async () => {
+ // The JOIN, not the pieces. backendCeiling() is pinned on its own and
+ // fetchBackendHealth's use of knownLatest is pinned on its own — but
+ // swapping `backendCeiling()` for `null` in readBackendHealth left the whole
+ // suite green, and with a null ceiling the stamp can never move forward
+ // again, which is the original bug back.
+ writeFileSync(stamp(), "1.0.13");
+ writeFileSync(
+ join(home, ".version-check.json"),
+ JSON.stringify({ latest: "0.9.3", backendLatest: "1.0.16", checkedAt: Date.now() }),
+ );
+ const { readBackendHealth } = await import("../commands/upgrade.js");
+
+ // Above the ceiling -> refused.
+ await readBackendHealth(
+ fakeClient("http://localhost:8090", { status: "ok", release_version: "99.0.0" }),
+ );
+ expect(tracked()).toBe("1.0.13");
+
+ // At the ceiling -> taken, which is only possible if the ceiling was read.
+ await readBackendHealth(
+ fakeClient("http://localhost:8090", { status: "ok", release_version: "1.0.16" }),
+ );
+ expect(tracked()).toBe("1.0.16");
+ });
+
+ it("does NOT record for a remote endpoint", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { fetchBackendHealth } = await import("../backend-version.js");
+ await fetchBackendHealth(
+ fakeClient("http://staging:8090", { status: "ok", release_version: "1.0.16" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("records nothing when the backend omits the field", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { fetchBackendHealth } = await import("../backend-version.js");
+ await fetchBackendHealth(
+ fakeClient("http://localhost:8090", { status: "ok" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("still refuses a claim above the ceiling, through this path too", async () => {
+ writeFileSync(stamp(), "1.0.13");
+ const { fetchBackendHealth } = await import("../backend-version.js");
+ await fetchBackendHealth(
+ fakeClient("http://localhost:8090", { status: "ok", release_version: "99.0.0" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(tracked()).toBe("1.0.13");
+ });
+
+ it("does not throw when a 200 carries a literally null body", async () => {
+ // A reachable backend answering 200 with `null` parses to null. If this
+ // bookkeeping threw, every caller catches (status.ts:53, ingest.ts:943) —
+ // and would report "backend not reachable" for a backend that answered.
+ // That wrong diagnosis would be produced by the recording step itself.
+ // None of the other fakes here return a non-object, so `health?.` was
+ // unpinned: dropping the `?` left all 25 tests green.
+ writeFileSync(stamp(), "1.0.13");
+ const { fetchBackendHealth } = await import("../backend-version.js");
+ const got = await fetchBackendHealth(
+ fakeClient("http://localhost:8090", null),
+ "1.0.16",
+ isNewer,
+ );
+ expect(got).toBeNull();
+ expect(tracked()).toBe("1.0.13");
+ });
+});
+
+/**
+ * The bounds are required parameters so that a CALL SITE cannot omit them. That
+ * says nothing about the callee: `checkBackendSchema` could accept both and
+ * quietly forward `null`, and every one of its own tests would still pass —
+ * backend-status.test.ts deliberately uses a remote endpoint, so the recorder
+ * never runs there at all. Mutating its forwarding call to pass `null` survived
+ * the entire src/cli/__tests__ suite before this block existed.
+ */
+describe("checkBackendSchema forwards its bounds rather than dropping them", () => {
+ let home: string;
+ let priorHome: string | undefined;
+
+ beforeEach(() => {
+ priorHome = process.env.IX_HOME;
+ home = mkdtempSync(join(tmpdir(), "ix-schema-bounds-"));
+ process.env.IX_HOME = home;
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.resetModules();
+ if (priorHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = priorHome;
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ const stamp = () => join(home, ".backend-version");
+ const tracked = () => (existsSync(stamp()) ? readFileSync(stamp(), "utf-8") : null);
+ const localClient = (health: unknown) =>
+ ({ endpoint: "http://localhost:8090", health: async () => health }) as unknown as IxClient;
+
+ it("passes the ceiling through even when the stamp is already ahead", async () => {
+ // With the stamp at 99.9.9 the no-ceiling rule would ACCEPT 5.0.0 as a
+ // correction downward, so only a real ceiling of 1.0.16 refuses it. What
+ // this case uniquely catches is a WRONG non-null ceiling: forwarding a
+ // permissive "99.0.0" kills it while the recording case below stays green.
+ writeFileSync(stamp(), "99.9.9");
+ const { checkBackendSchema } = await import("../backend-status.js");
+ await checkBackendSchema(
+ localClient({ status: "ok", schema_version: 3, release_version: "5.0.0" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(tracked()).toBe("99.9.9");
+ });
+
+ it("still records a legitimate release through this path", async () => {
+ // ...and the block above is not passing merely because nothing records.
+ writeFileSync(stamp(), "1.0.13");
+ const { checkBackendSchema } = await import("../backend-status.js");
+ await checkBackendSchema(
+ localClient({ status: "ok", schema_version: 3, release_version: "1.0.16" }),
+ "1.0.16",
+ isNewer,
+ );
+ expect(tracked()).toBe("1.0.16");
+ });
+});
+
+describe("isLocalEndpoint", () => {
+ it("accepts the local backend the notice is about", async () => {
+ const { isLocalEndpoint } = await import("../backend-version.js");
+ for (const e of [
+ "http://localhost:8090",
+ "http://127.0.0.1:8090",
+ "http://[::1]:8090",
+ "http://127.0.0.2:8090", // all of 127.0.0.0/8 is loopback
+ "http://0.0.0.0:8090", // what client/api.ts and errors.ts already accept
+ "http://localhost.:8090", // the fully-qualified form resolvers accept
+ ]) {
+ expect(isLocalEndpoint(e)).toBe(true);
+ }
+ });
+
+ it("rejects a remote deployment", async () => {
+ // The stamp is global but the endpoint is per invocation, so
+ // `IX_ENDPOINT=http://staging:8090 ix status` would otherwise record a
+ // different deployment's release into the file that governs the LOCAL
+ // docker image notice.
+ const { isLocalEndpoint } = await import("../backend-version.js");
+ for (const e of [
+ "http://staging:8090",
+ "https://ix.example.com",
+ "http://10.0.0.5:8090",
+ // Remote NAMES that merely start "127." — a prefix match on the hostname
+ // made these local, which is the opposite of what this function is for.
+ "http://127.0.0.1.evil.com:8090",
+ "http://127.example.com:8090",
+ ]) {
+ expect(isLocalEndpoint(e)).toBe(false);
+ }
+ });
+
+ it("rejects an unparseable endpoint rather than assuming local", async () => {
+ const { isLocalEndpoint } = await import("../backend-version.js");
+ expect(isLocalEndpoint("not a url")).toBe(false);
+ });
+});
+
+/**
+ * Recording happens inside the one function that fetches health, so forgetting
+ * it is not a mistake a new call site can make. This pins that there is still
+ * exactly one such function — the property that makes the design work.
+ */
+describe("health is fetched in exactly one place", () => {
+ const SRC = join(HERE, "..", "..");
+
+ const walk = (dir: string): string[] =>
+ readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
+ if (e.name === "__tests__" || e.name === "node_modules") return [];
+ const full = join(dir, e.name);
+ // .ts .js .mts .cts .mjs .cjs — not just .ts. src/ happens to be all .ts
+ // today, so a future .mts or .js under it would be invisible to BOTH
+ // guards below and neither would report anything missing. Not .tsx/.jsx:
+ // there is no JSX in this CLI, and adding some would be the point at
+ // which to revisit this.
+ return e.isDirectory() ? walk(full) : /\.(m|c)?(t|j)s$/.test(e.name) ? [full] : [];
+ });
+
+ // Any receiver, not just one literally named `client`: a renamed local would
+ // otherwise drop the file out of the search entirely.
+ const callers = walk(SRC)
+ .map((f) => ({ file: f, src: readFileSync(f, "utf-8") }))
+ // Comments stripped first: this codebase names functions in call syntax in
+ // prose constantly, and a doc comment mentioning client.health() would fail
+ // CI with a message pointing at the wrong problem.
+ //
+ // Only comments that START a line. A blanket `//` strip is string-blind:
+ // the `//` inside `http://localhost:8090` — the most common literal in this
+ // file family — swallowed the rest of that line, so a real `.health()` call
+ // sharing a line with a URL became invisible to the guard. Verified. Block
+ // comments are left alone for the same reason: a `**/*.ts` glob literal ate
+ // from the string to the next `*/` and dropped the chokepoint itself.
+ .map((f) => ({ ...f, src: f.src.replace(/^\s*(\/\/|\*|\/\*).*$/gm, "") }))
+ .filter((f) => /\.health\s*\(\s*\)/.test(f.src))
+ .map((f) => f.file.slice(SRC.length + 1).replace(/\\/g, "/"));
+
+ it("finds the health callers at all", () => {
+ // NOT a vacuity guard — the assertion below is an exact toEqual against a
+ // one-element literal, which rejects [] on its own. This exists only so a
+ // broken `walk` fails saying "found nothing" instead of producing a deep
+ // -equal diff that reads like the chokepoint moved.
+ expect(callers.length).toBeGreaterThan(0);
+ });
+
+ // The `.health()` search above cannot see a raw `fetch(`${e}/v1/health`)`, so
+ // pin who may name the path at all, and how many times.
+ //
+ // READ THIS BEFORE TRUSTING IT. Three rounds of review have established what
+ // this does and does not catch, and the honest summary is narrow:
+ //
+ // CAUGHT: a new file that names the path INLINE. A second inline use of it
+ // inside a listed file. Removing a listed use (so the list cannot go stale
+ // silently, which is the whole reason it is here and not in a comment).
+ //
+ // NOT CAUGHT: a new reader inside a listed file that reuses the existing
+ // constant — `fetch(HEALTH_URL).json()` added to docker.ts counts zero new
+ // literals and passes. Nor a path assembled from fragments
+ // (`"/v1" + "/health"`). Both verified. So the three listed files are
+ // checked against INLINE uses and trusted against INDIRECTION.
+ //
+ // What actually stops a body read in the two readiness-poll files is that
+ // both use `curl` with stdio ignored and discard the response. That is not
+ // true of the third: `client/api.ts` is the one place that DOES read a health
+ // body, via `get()` → `resp.json()`, and it is listed precisely because
+ // everything legitimate goes through it.
+ //
+ // Comment handling: line-start block comments, line-start `//`, and line-start
+ // `*` (doc-continuation lines) are stripped. Trailing `//` is deliberately NOT,
+ // and that is a considered trade. A `(^|[^:])//` rule was tried and silently
+ // erased three real spellings — `` `${proto}//${host}/v1/health` ``,
+ // `"//localhost:8090/..."`, and a doubled-slash template — because the `//`
+ // sat after `}` or `"`. A guard that quietly stops seeing real calls is far
+ // worse than one that trips on prose: a false positive is a confusing red CI,
+ // a false negative is no guard at all. So prose naming the path in a trailing
+ // comment WILL fail this test. That is intended; move it to a line-start one.
+ //
+ // Known false positives, unfixed, both failing red rather than silently:
+ // a block comment containing a `**/` glob ends the strip early, because `**/`
+ // CONTAINS `*/` — position has nothing to do with it. That only surfaces when
+ // the block's continuation lines do NOT begin with `*`, since the line-start
+ // `*` rule strips those anyway, so ordinary JSDoc is unaffected. A block
+ // comment opened mid-line is never stripped at all.
+ const pathCounts = Object.fromEntries(
+ walk(SRC)
+ .map((f) => ({
+ file: f,
+ src: readFileSync(f, "utf-8")
+ .replace(/^[ \t]*\/\*[\s\S]*?\*\//gm, "")
+ .replace(/^\s*(\/\/|\*|\/\*).*$/gm, ""),
+ }))
+ .map((f) => ({ ...f, n: (f.src.match(/v1\/health/g) ?? []).length }))
+ .filter((f) => f.n > 0)
+ .map((f) => [f.file.slice(SRC.length + 1).replace(/\\/g, "/"), f.n]),
+ );
+
+ it("finds the health-path users at all", () => {
+ expect(Object.keys(pathCounts).length).toBeGreaterThan(0);
+ });
+
+ it("has only the readiness polls and the client naming /v1/health", () => {
+ expect(pathCounts).toEqual({
+ // The two readiness polls. Both `curl -sf` with stdio ignored, so they
+ // discard the response: there is no body to record and they are correctly
+ // outside the chokepoint.
+ "cli/commands/docker.ts": 1,
+ "cli/commands/upgrade.ts": 1,
+ // The one real request, and the one place a health body is read. As the
+ // code stands today everything reaches it through IxClient.health(),
+ // which the assertion below routes through this module — but that is a
+ // fact about the current tree, not something this guard enforces: a body
+ // read added to a listed file is documented above as not caught.
+ "client/api.ts": 1,
+ });
+ });
+
+ it("has only backend-version.ts calling .health()", () => {
+ // Exactly one, across the WHOLE src tree — not just src/cli, which left
+ // src/mcp (it already exposes an ix_health tool) and src/client invisible.
+ // backend-status.ts used to be exempted on a cycle that does not exist:
+ // backend-version.ts imports only node builtins and two erased type
+ // imports, so it now goes through the chokepoint like everything else.
+ expect(callers.sort()).toEqual(["cli/backend-version.ts"]);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/backend-status.test.ts b/ix-cli/src/cli/__tests__/backend-status.test.ts
index cdfa4a26..3ca30ea3 100644
--- a/ix-cli/src/cli/__tests__/backend-status.test.ts
+++ b/ix-cli/src/cli/__tests__/backend-status.test.ts
@@ -9,9 +9,13 @@ import {
type BackendContainer,
} from "../backend-status.js";
import type { IxClient } from "../../client/api.js";
+import { isNewer } from "../commands/upgrade.js";
+// `endpoint` matters now: checkBackendSchema records through the shared health
+// fetch, and the recorder is gated on the endpoint being local. A remote one
+// keeps these unit tests from touching any stamp file at all.
function fakeClient(health: () => Promise<any>): IxClient {
- return { health } as unknown as IxClient;
+ return { endpoint: "http://schema-spec.invalid:8090", health } as unknown as IxClient;
}
function container(overrides: Partial<BackendContainer>): BackendContainer {
@@ -28,24 +32,28 @@ function container(overrides: Partial<BackendContainer>): BackendContainer {
describe("checkBackendSchema", () => {
it("matches when the backend reports the expected version", async () => {
- const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok", schema_version: CLIENT_EXPECTED_SCHEMA_VERSION })));
+ const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok", schema_version: CLIENT_EXPECTED_SCHEMA_VERSION })), null, isNewer);
expect(s).toEqual({ reachable: true, serverVersion: CLIENT_EXPECTED_SCHEMA_VERSION, expected: CLIENT_EXPECTED_SCHEMA_VERSION, matches: true });
});
it("flags a mismatch when the persisted graph predates the engine", async () => {
- const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok", schema_version: CLIENT_EXPECTED_SCHEMA_VERSION - 1 })));
+ const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok", schema_version: CLIENT_EXPECTED_SCHEMA_VERSION - 1 })), null, isNewer);
expect(s.matches).toBe(false);
expect(s.serverVersion).toBe(CLIENT_EXPECTED_SCHEMA_VERSION - 1);
});
it("does not flag when the backend reports no schema version (can't prove stale)", async () => {
- const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok" })));
+ const s = await checkBackendSchema(fakeClient(async () => ({ status: "ok" })), null, isNewer);
expect(s.matches).toBe(true);
expect(s.serverVersion).toBeNull();
});
it("reports unreachable (and does not flag) when health throws", async () => {
- const s = await checkBackendSchema(fakeClient(async () => { throw new Error("ECONNREFUSED"); }));
+ const s = await checkBackendSchema(
+ fakeClient(async () => { throw new Error("ECONNREFUSED"); }),
+ null,
+ isNewer,
+ );
expect(s).toEqual({ reachable: false, serverVersion: null, expected: CLIENT_EXPECTED_SCHEMA_VERSION, matches: true });
});
});
diff --git a/ix-cli/src/cli/backend-status.ts b/ix-cli/src/cli/backend-status.ts
index 6b377cb5..e9d42926 100644
--- a/ix-cli/src/cli/backend-status.ts
+++ b/ix-cli/src/cli/backend-status.ts
@@ -16,6 +16,7 @@ import { execFileSync } from "node:child_process";
import { join } from "node:path";
import { homedir } from "node:os";
import type { IxClient } from "../client/api.js";
+import { fetchBackendHealth } from "./backend-version.js";
export const BACKEND_IMAGE = "ghcr.io/ix-infrastructure/ix-memory-layer";
const BACKEND_PORT = "8090";
@@ -136,11 +137,29 @@ export interface BackendSchemaStatus {
matches: boolean;
}
-/** Read the backend's reported schema_version and compare to what we expect. */
-export async function checkBackendSchema(client: IxClient): Promise<BackendSchemaStatus> {
+/**
+ * Read the backend's reported schema_version and compare to what we expect.
+ *
+ * Also RECORDS the release the backend reports, as a side effect of going
+ * through the shared health fetch — the same as every other health call site.
+ */
+export async function checkBackendSchema(
+ client: IxClient,
+ // REQUIRED, not defaulted. Defaults of `null` + `() => false` turn off the
+ // ceiling AND the no-ceiling fallback at once, so a caller that omitted them
+ // would record any version-shaped claim a local container made — the exact
+ // 99.0.0 case recordBackendRelease exists to refuse. This is a published
+ // export, so "a call site can get it wrong" has to be impossible, not
+ // discouraged.
+ knownLatest: string | null,
+ isNewer: (a: string, b: string) => boolean,
+): Promise<BackendSchemaStatus> {
const expected = CLIENT_EXPECTED_SCHEMA_VERSION;
try {
- const health = await client.health();
+ // Through the chokepoint, so this records like every other health fetch —
+ // there is no cycle: backend-version.ts imports only node builtins and two
+ // erased `import type`s.
+ const health = await fetchBackendHealth(client, knownLatest, isNewer);
const serverVersion = typeof health.schema_version === "number" ? health.schema_version : null;
// No reported version (older backend) is treated as a match: we can't prove
// staleness, and the ingest path already forces a re-ingest when it can.
diff --git a/ix-cli/src/cli/backend-version.ts b/ix-cli/src/cli/backend-version.ts
new file mode 100644
index 00000000..7ef847a0
--- /dev/null
+++ b/ix-cli/src/cli/backend-version.ts
@@ -0,0 +1,192 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
+import { dirname, join } from "path";
+import { homedir } from "os";
+
+import type { IxClient } from "../client/api.js";
+import type { HealthResponse } from "../client/types.js";
+
+/**
+ * Everything that reads or writes `~/.ix/.backend-version`.
+ *
+ * A leaf on purpose. `upgrade.ts` owns the update notice and imports
+ * `backend-status.ts`, so the stamp could not live in either without a cycle the
+ * moment `backend-status` needed to write it. Keeping it here lets the ONE
+ * function that fetches health also record what it read, which is what stops a
+ * future call site from silently forgetting to.
+ */
+
+const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
+
+/** The release the backend is believed to be running. */
+export const BACKEND_VERSION_FILE = join(IX_HOME, ".backend-version");
+
+/**
+ * The one definition of a valid version string, imported by upgrade.ts too.
+ *
+ * Copied rather than shared once already, and this exact pattern has shipped
+ * broken: written as a single `(?:[-+]...)?` group whose class omitted `+`, it
+ * rejected the valid tag `0.9.0-rc.1+abc1234` and `ix upgrade` exited 1 with
+ * "Could not reach GitHub" against a perfectly reachable GitHub. Two copies mean
+ * the next correction lands in one of them.
+ */
+export const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+/** Longer than any plausible tag; bounds a value the container controls. */
+const MAX_VERSION_LENGTH = 64;
+
+export function getTrackedVersion(versionFile: string): string {
+ try {
+ if (!existsSync(versionFile)) return "0.0.0";
+ return readFileSync(versionFile, "utf-8").trim() || "0.0.0";
+ } catch {
+ return "0.0.0";
+ }
+}
+
+/**
+ * Record a version stamp. Returns whether it was written.
+ *
+ * `mkdirSync` because IX_HOME may not exist yet. A falsy version is refused: not
+ * knowing which release we are on is not the same as being on none of them.
+ *
+ * NOT atomic, deliberately. `writeFileSync` opens with O_TRUNC, so a reader
+ * landing mid-write sees "" and is told a current backend is out of date — and
+ * this is now reachable from `ix status`/`ix map` while `checkForUpdate` reads
+ * the file on every command. Two things make that the better trade anyway:
+ * `recordBackendRelease` short-circuits when the stamp already agrees, so a
+ * write happens only when the backend's version actually CHANGES, not per
+ * command; and a temp-file-plus-rename replaces a file the caller may not have
+ * permission to write, since rename needs the directory rather than the file.
+ * That would silently change when the stamp-failure warning fires and would
+ * force the tests that pin it onto read-only directories, which Windows does not
+ * honour. Worth revisiting with an injection that works on both platforms.
+ */
+export function writeVersionStamp(
+ versionFile: string,
+ version: string | null | undefined,
+): boolean {
+ if (!version) return false;
+ try {
+ mkdirSync(dirname(versionFile), { recursive: true });
+ writeFileSync(versionFile, version);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Record what the backend says it is running.
+ *
+ * `.backend-version` was a record of what the CLI last INSTALLED, which is the
+ * same thing as what is RUNNING only while nothing else moves the image. Pull
+ * through docker compose and the file names an older release than the container,
+ * so the update notice fires on every command for ever. The container is the one
+ * thing that always knows, so it is asked rather than inferred.
+ *
+ * Three things bound a value the container controls, because this file decides
+ * whether the user is ever told about an upgrade again:
+ *
+ * - it is trimmed before matching. `getTrackedVersion` trims on the way out, and
+ * JavaScript's `$` does not match before a trailing newline, so without this a
+ * value from an --env-file or a ConfigMap silently fails the shape test and
+ * the whole feature no-ops with nothing to see.
+ * - it must be version-shaped and bounded in length. It is an env var an
+ * operator can set to anything.
+ * - it may NOT claim to be newer than the newest release we know of. Otherwise
+ * one container reporting `99.0.0` — a typo in a compose override, or a
+ * tampered image — permanently silences the notice AND makes `ix upgrade`
+ * report "already on the latest version" without ever pulling, so a security
+ * release can never reach that machine. When no release is known yet, only
+ * corrections that do not move the stamp forward are accepted, which still
+ * repairs a stamp stuck ahead and defers the rest until the cache exists.
+ *
+ * What the ceiling does NOT stop, stated plainly: a container that reports
+ * *exactly* the ceiling is accepted, and a compromised one has outbound network
+ * and can simply read the public release feed to learn that number rather than
+ * guess it. It then reaches the same silenced state by looking the answer up.
+ * This is a capability the feature introduces — before it, the stamp was
+ * written only by our own install/pull paths, so a container could not
+ * influence it at all. It is accepted deliberately: the alternative is to
+ * distrust the only component that actually knows what it is running, and the
+ * fail-safe direction (a container under-reporting, causing an unnecessary
+ * pull) is the one that stays open. `ix doctor`'s digest comparison remains the
+ * check that does not ask the container what it is.
+ */
+export function recordBackendRelease(
+ reported: string | null | undefined,
+ knownLatest: string | null | undefined,
+ isNewer: (a: string, b: string) => boolean,
+): boolean {
+ const value = typeof reported === "string" ? reported.trim() : "";
+ if (!value || value.length > MAX_VERSION_LENGTH || !VERSION_RE.test(value)) return false;
+
+ const tracked = getTrackedVersion(BACKEND_VERSION_FILE);
+ if (value === tracked) return false; // already agrees; do not touch the file
+
+ const ceiling =
+ typeof knownLatest === "string" && VERSION_RE.test(knownLatest.trim())
+ ? knownLatest.trim()
+ : null;
+ // No published release can be older than what a container legitimately runs.
+ if (ceiling ? isNewer(value, ceiling) : isNewer(value, tracked)) return false;
+
+ return writeVersionStamp(BACKEND_VERSION_FILE, value);
+}
+
+/**
+ * True when this endpoint is the local backend the update notice is about.
+ *
+ * The stamp is global (`~/.ix/.backend-version`) but the endpoint is per
+ * invocation, so `IX_ENDPOINT=http://staging:8090 ix status` would otherwise
+ * record a different deployment's release into the file that governs the LOCAL
+ * docker image notice — a newer remote silencing a genuinely stale local
+ * backend, or an older one nagging about a current one.
+ */
+export function isLocalEndpoint(endpoint: string): boolean {
+ try {
+ // A trailing dot is the fully-qualified form and resolvers accept it.
+ const host = new URL(endpoint).hostname.toLowerCase().replace(/\.$/, "");
+ return (
+ host === "localhost" ||
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || // 127.0.0.0/8, as an ADDRESS
+ // ...not a prefix: `127.0.0.1.evil.com` is a remote name that starts "127."
+ host === "0.0.0.0" || // what client/api.ts and errors.ts already accept
+ host === "[::1]" // new URL() always brackets IPv6, so bare "::1" is unreachable
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Fetch `/v1/health` AND record the release it reports.
+ *
+ * The single place either happens. Every command that READS a health body goes
+ * through here, so "a new call site forgot to record" is not a mistake that can
+ * be made — which is worth more than the grep-based drift guard it replaces.
+ *
+ * Precisely: reads of the body. docker.ts and upgrade.ts also hit /v1/health via
+ * `curl -sf` with stdio ignored, purely as a readiness poll; they discard the
+ * response, so there is nothing there to record.
+ */
+export async function fetchBackendHealth(
+ client: IxClient,
+ knownLatest: string | null | undefined,
+ isNewer: (a: string, b: string) => boolean,
+): Promise<HealthResponse> {
+ const health = await client.health();
+ // From the client the request actually went to. Taking it as a second
+ // argument reintroduced exactly the "a call site can get it wrong" mistake
+ // this module exists to make impossible.
+ // `health?.` because a 200 whose body is literally `null` parses to null.
+ // The contract of this function is "return whatever the backend sent"; adding
+ // a throw of its own would be this bookkeeping changing the outcome of a
+ // request that succeeded. Nothing more is claimed: status.ts dereferences
+ // health.status unguarded moments later, so on a null body it fails either
+ // way — the `?.` keeps the failure the caller's, not ours.
+ if (isLocalEndpoint(client.endpoint)) {
+ recordBackendRelease(health?.release_version, knownLatest, isNewer);
+ }
+ return health;
+}
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 0f3da14f..b2c0bfbd 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -6,6 +6,7 @@ import chalk from "chalk";
import { IxClient } from "../client/api.js";
import { getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";
import { workspaceIdForPath } from "./system.js";
+import { readBackendHealth } from "./commands/upgrade.js";
export interface BootstrapResult {
createdConfig: boolean;
@@ -124,9 +125,13 @@ export function resolveWorkspaceId(cwd = process.cwd()): string | undefined {
* Ensure the backend is reachable. If not, auto-start via ix docker start.
*/
export async function ensureBackendAvailable(): Promise<void> {
- const client = new IxClient(getEndpoint());
+ const endpoint = getEndpoint();
+ const client = new IxClient(endpoint);
try {
- await client.health();
+ // Through readBackendHealth so this probe records the release the backend
+ // reports, like every other health fetch. `ix init` never reaches the
+ // ingest path, so without this it would never record at all.
+ await readBackendHealth(client);
} catch {
try {
execFileSync("ix", ["docker", "start"], { stdio: "inherit", timeout: 120000 });
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index 8ba94d01..59b93e74 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -13,6 +13,7 @@ import {
checkBackendSchema,
isNonStandardBackend,
} from "../backend-status.js";
+import { backendCeiling, isNewer, readBackendHealth } from "./upgrade.js";
interface CheckResult {
ok: boolean;
@@ -124,7 +125,9 @@ export function registerDoctorCommand(program: Command): void {
name: "Server reachable",
run: async () => {
try {
- const h = await client.health();
+ // Records what the backend says it is running; see
+ // backend-version.ts. Free — this response is already needed.
+ const h = await readBackendHealth(client);
return { ok: h.status === "ok", detail: `${endpoint} → ${h.status}` };
} catch (e: any) {
return { ok: false, detail: e.message ?? "unreachable" };
@@ -207,7 +210,7 @@ export function registerDoctorCommand(program: Command): void {
// Ix#271: a graph written by an older engine fails scoped reads silently.
name: "Graph schema matches engine",
run: async () => {
- const s = await checkBackendSchema(client);
+ const s = await checkBackendSchema(client, backendCeiling(), isNewer);
if (!s.reachable) return { ok: true, detail: "backend unreachable (skipped)" };
if (s.serverVersion === null) return { ok: true, detail: "backend does not report a schema version" };
if (s.matches) return { ok: true, detail: `schema v${s.serverVersion}` };
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 31e4c959..2d929bcf 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -18,6 +18,7 @@ import { loadIngestionModules } from './ingestion-loader.js';
import { ensureWorkspaceIdState } from '../bootstrap.js';
import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';
import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';
+import { readBackendHealth } from './upgrade.js';
import { SUPPORTED_EXTENSIONS } from '../supported-extensions.js';
import { canRenderProgress } from '../stderr.js';
import { createTypeScriptModuleResolver } from '../ts-module-resolution.js';
@@ -940,7 +941,7 @@ export async function ingestFiles(
// absolute→relative source_uri migration, or folding workspace_id into ids).
// CLIENT_EXPECTED_SCHEMA_VERSION is shared with doctor/upgrade (backend-status).
try {
- const health = await client.health();
+ const health = await readBackendHealth(client);
const serverVersion = (health as any)?.schema_version;
if (typeof serverVersion === 'number' && serverVersion !== CLIENT_EXPECTED_SCHEMA_VERSION) {
process.stderr.write(
diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.ts
index 68df36af..a70169e2 100644
--- a/ix-cli/src/cli/commands/status.ts
+++ b/ix-cli/src/cli/commands/status.ts
@@ -1,6 +1,7 @@
import type { Command } from "commander";
import { renderSection, renderKeyValue, renderWarning, renderNote, renderSuccess } from "../ui.js";
import { IxClient } from "../../client/api.js";
+import { readBackendHealth } from "./upgrade.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { detectStaleFiles } from "../stale.js";
import { llmError, llmLine, printLlmLines } from "../llm.js";
@@ -50,7 +51,7 @@ export function registerStatusCommand(program: Command): void {
.action(async (opts: { format: string; root?: string }) => {
const client = new IxClient(getEndpoint());
try {
- const health = await client.health();
+ const health = await readBackendHealth(client);
const root = resolveWorkspaceRoot(opts.root);
// Detect stale files
diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.ts
index 9ab0a8e9..34e3d078 100644
--- a/ix-cli/src/cli/commands/upgrade.ts
+++ b/ix-cli/src/cli/commands/upgrade.ts
@@ -7,6 +7,40 @@ import { homedir } from "os";
import chalk from "chalk";
import { BACKEND_IMAGE, checkBackendImage, isNonStandardBackend } from "../backend-status.js";
import { canRenderProgress } from "../stderr.js";
+import type { IxClient } from "../../client/api.js";
+import {
+ BACKEND_VERSION_FILE,
+ VERSION_RE,
+ fetchBackendHealth,
+ getTrackedVersion,
+ writeVersionStamp,
+} from "../backend-version.js";
+
+// Re-exported for the existing importers of this module (tests and call sites
+// that predate backend-version.ts). recordBackendRelease is deliberately NOT
+// among them: it is reached only through fetchBackendHealth, and re-exporting
+// it here would advertise a second way in.
+export { BACKEND_VERSION_FILE, VERSION_RE, writeVersionStamp } from "../backend-version.js";
+
+/**
+ * Fetch health and record what the backend says it is running.
+ *
+ * The one entry point commands use, so the cache lookup and the version
+ * comparison live in exactly one place — and so no call site can fetch health
+ * without recording, which is the mistake a grep-based guard could only detect
+ * after the fact.
+ */
+/** The newest backend release the CLI knows of; the ceiling a container may claim. */
+export function backendCeiling(): string | null {
+ return readCache()?.backendLatest ?? null;
+}
+
+export async function readBackendHealth(client: IxClient) {
+ // backendLatest, NOT latest: `latest` is the CLI's own release series, so a
+ // ceiling taken from it would refuse every legitimate container report for
+ // ever — silently reinstating the bug this exists to fix.
+ return fetchBackendHealth(client, backendCeiling(), isNewer);
+}
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -19,7 +53,6 @@ const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
const VERSION_CACHE = join(IX_HOME, ".version-check.json");
const COMPASS_DIR = join(IX_HOME, "cli", "compass");
const COMPASS_VERSION_FILE = join(COMPASS_DIR, ".version");
-const BACKEND_VERSION_FILE = join(IX_HOME, ".backend-version");
interface VersionCache {
latest: string;
@@ -49,7 +82,6 @@ function getCurrentVersion(): string {
// — `0.9.0-rc.1+abc1234`, valid semver — failed the test. fetchLatestRelease
// then returned null and `ix upgrade` reported "Could not reach GitHub to check
// for updates" and exited 1 against a perfectly reachable GitHub.
-export const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
async function fetchLatestRelease(
repo: string,
@@ -341,14 +373,7 @@ function shouldOfferCompassUpgrade(compassLatest: string | undefined): boolean {
return shouldOfferCompassUpgradeFor(compassLatest, installedCompass());
}
-function getTrackedVersion(versionFile: string): string {
- try {
- if (!existsSync(versionFile)) return "0.0.0";
- return readFileSync(versionFile, "utf-8").trim() || "0.0.0";
- } catch {
- return "0.0.0";
- }
-}
+
/**
* Whether to tell the user their backend is behind.
@@ -426,41 +451,6 @@ export function stampDisagreesWithPull(trackedVersion: string, pulled: string):
return isNewer(trackedVersion, pulled) || isNewer(pulled, trackedVersion);
}
-/**
- * Record the backend release in its stamp file. Returns whether it was written.
- *
- * `mkdirSync` because IX_HOME may not exist yet — a stamp that fails to write
- * leaves the tracked version behind for ever, and the notice it drives says
- * "update available" on every command with no way for the user to see why.
- *
- * A falsy version is refused rather than written: not knowing which release we
- * are on is not the same as being on none of them. Being wrong *behind* costs a
- * nag, while being wrong *ahead* hides a genuinely stale backend and stops
- * `ix upgrade` from ever fetching it — so where there is a choice, this errs
- * behind. (It is not always a choice: the GHCR `:latest` tag and the
- * `ix-memory-layer-dist` release are separate publishing surfaces with nothing
- * correlating them, so a release cut between the two can be recorded ahead of
- * the image actually pulled. `ix upgrade` has always had that race; correcting
- * it needs the backend to report its own version.)
- *
- * The write does not throw — callers differ on whether a failure should be
- * fatal, so they decide from the return value rather than from an exception.
- * Not a general component-stamp writer: the compass stamp is written with a
- * trailing newline that `parseCompassStamp` depends on.
- */
-export function writeVersionStamp(
- versionFile: string,
- version: string | null | undefined,
-): boolean {
- if (!version) return false;
- try {
- mkdirSync(dirname(versionFile), { recursive: true });
- writeFileSync(versionFile, version);
- return true;
- } catch {
- return false;
- }
-}
/**
* Whether this compose file runs the backend from the moving `:latest` tag.
diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.ts
index acfefe80..3fabacd4 100644
--- a/ix-cli/src/client/api.ts
+++ b/ix-cli/src/client/api.ts
@@ -25,7 +25,9 @@ export class IxClient {
// per-request timeouts (5-30 min each), the whole operation aborts and the
// process exits instead of grinding for hours and stacking with re-launches.
constructor(
- private endpoint: string = "http://localhost:8090",
+ // readonly so callers can ask which endpoint a response came FROM, rather
+ // than being handed a second string that is only equal by inspection.
+ public readonly endpoint: string = "http://localhost:8090",
private deadlineSignal?: AbortSignal,
) {}
diff --git a/ix-cli/src/client/types.ts b/ix-cli/src/client/types.ts
index 3e8b6b08..32e66f49 100644
--- a/ix-cli/src/client/types.ts
+++ b/ix-cli/src/client/types.ts
@@ -154,6 +154,14 @@ export interface HealthResponse {
// differs from this, it forces a clean re-ingest (e.g. absolute→relative
// source_uri migration changes every node ID).
schema_version?: number;
+ // The published release the running container was built as, when it knows.
+ // Absent from any backend older than Ix-memory#157, and from any image not
+ // built by the release pipeline — both mean "fall back to what you tracked".
+ // This is the container's own claim, not proof: it is an env var, so
+ // `docker run -e` overrides it. It is the right answer to "what do you think
+ // you are" and the wrong one to "what are you really", which is what
+ // checkBackendImage's digest comparison is for.
+ release_version?: string;
}
export interface PatchSource {