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): stop comparing compass versions across two unrelated series (#391)
KageBinaryaf23b558efea
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4c2711b5..b769f2d8 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -59,6 +59,13 @@ jobs:compass:if: ${{ github.event_name != 'pull_request' }}runs-on: ubuntu-latest+ outputs:+ # The system-compass commit this bundle was built from. Recorded in the+ # bundle's .version stamp so a build is identifiable after the fact —+ # system-compass's package.json version is not maintained against the+ # ix-compass-dist release series (it read 0.2.0 while dist was on v0.3.0),+ # so the commit is the only reliable identity the bundle has.+ sha: ${{ steps.build-compass.outputs.sha }}steps:- name: Set up Node.jsuses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0@@ -70,6 +77,7 @@ jobs:# a fully green release that shipped an empty compass/ directory and a# broken `ix view` for every user. A compass failure must fail the release.- name: Build System Compass+ id: build-compassenv:COMPASS_TOKEN: ${{ secrets.COMPASS_TOKEN }}run: |@@ -98,6 +106,9 @@ jobs:exit 1}cd system-compass+ # Capture the source commit before building, so the stamp written in+ # the package job can identify this bundle (see the job's `outputs`).+ echo "sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"npm ci --legacy-peer-depsnpm run buildif [ ! -f dist/index.html ]; then@@ -256,6 +267,9 @@ jobs:# A PR dry-run skips the compass job, so an absent bundle is expected# there and only there.REQUIRE_COMPASS: ${{ github.event_name != 'pull_request' }}+ # Empty on a PR dry-run (the compass job is skipped); the stamp falls+ # back to `unknown`, which is fine because no bundle is staged either.+ COMPASS_SHA: ${{ needs.compass.outputs.sha }}run: |STAGING="ix-${VERSION}-${TARGET}"# Compute the checksum with node (always present on every runner);@@ -282,16 +296,33 @@ jobs:# Windows an unrelated tar failure masked it, and everywhere else the# swap succeeded and silently reverted the map to a June build.#- # The Ix version rather than a compass version: the bundle is built- # from compass main at release time, so it is always at least as new- # as any ix-compass-dist release cut before it. That makes the Ix- # version a monotonic stand-in, and isNewer() still offers a genuine- # dist upgrade published later at a higher number.+ # The `+release.<sha>` marker is load-bearing, not decoration. This+ # bundle is built from system-compass main and has no+ # ix-compass-dist release number, so the version recorded here is an+ # *Ix* version. install.sh and the compass-upgrade path write the+ # same file with a *dist* version. Until v0.9.2 the stamp was a bare+ # number with no way to tell the two apart, so+ # `isNewer(distLatest, stamp)` compared two unrelated series and was+ # correct only while Ix's numbers happened to be the larger ones —+ # the first dist tag above the running Ix version would have+ # replaced this newer bundle with an older dist build (Ix#376). The+ # marker lets the CLI skip the comparison entirely for release+ # bundles, which is the only correct answer: a dist release+ # published after this one arrives with the next Ix release, which+ # bundles main again.#- # install.sh writes this same file after extracting, using the dist- # release number. Either value suppresses the spurious update; the- # stamp being present at all is what matters.- printf '%s' "$VERSION" > "$STAGING/compass/.version"+ # ONE LINE, and semver build metadata rather than key=value. This+ # file has readers we cannot upgrade: every already-shipped CLI+ # reads it with `readFileSync(...).trim()` — the whole file — and+ # feeds that to splitVersion. A multi-line stamp makes the major+ # parse as NaN -> 0, so an old CLI sees a 1.x release as [0,0,0] and+ # downloads ix-compass-dist over the newer bundle it just installed:+ # Ix#376 again, reintroduced by the format change, on exactly the+ # upgrade that ships the fix. splitVersion drops everything after+ # `+`, so old CLIs read this as a plain "$VERSION" and behave as+ # they do today. Do not add a second line, and do not drop the `+`.+ printf '%s+release.%s\n' \+ "$VERSION" "${COMPASS_SHA:-unknown}" > "$STAGING/compass/.version"test -s "$STAGING/compass/.version" \|| { echo "::error::failed to stamp $STAGING/compass/.version"; exit 1; }COMPASS_STAGED=1diff --git a/ix-cli/src/cli/__tests__/upgrade-compass-stamp-producers.test.ts b/ix-cli/src/cli/__tests__/upgrade-compass-stamp-producers.test.tsnew file mode 100644index 00000000..3ef64b43--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-compass-stamp-producers.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { parseCompassStamp } from "../commands/upgrade.js";++/**+ * `compass/.version` has three producers and one reader, in different languages,+ * none of which import each other:+ *+ * .github/workflows/release.yml the bundle shipped inside a release tarball+ * scripts/install/install.sh a tarball that predates the stamp+ * scripts/install/install.ps1 the same, on Windows+ * parseCompassStamp() the reader, in this package+ *+ * Nothing else couples them. The producers are shell/YAML string literals, so a+ * change there typecheks nowhere and no unit test touching only the reader can+ * notice — which is exactly how #376 happened in the first place, and how the+ * multi-line `key=value` shape nearly shipped.+ *+ * These cases read the real files and push the literal each one writes through+ * the real parser. Two properties matter:+ *+ * 1. **It parses as a release bundle.** A producer that loses its `+release`+ * marker silently re-labels its bundle dist-series, and `ix upgrade` will+ * downgrade it to an older ix-compass-dist build.+ * 2. **It stays on ONE line.** Every already-shipped CLI reads this file with+ * `readFileSync(...).trim()` — the whole file — and feeds it to+ * `splitVersion`. A second line makes the major parse as NaN -> 0, so an old+ * CLI sees a 1.x release as [0,0,0] and replaces the newer bundle it just+ * installed with ix-compass-dist. The reader we control cannot fix that;+ * only the producers can, by never writing a second line.+ */+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");+const read = (p: string) => readFileSync(join(REPO_ROOT, p), "utf-8");++/** What the producer's format literal renders to for a given version. */+const SAMPLE_VERSION = "1.4.2";+const SAMPLE_SHA = "7f98724";++describe("compass .version producers agree with parseCompassStamp", () => {+ const cases: { name: string; file: string; render: (src: string) => string }[] = [+ {+ name: "release.yml (release tarball)",+ file: ".github/workflows/release.yml",+ render: (src) => {+ // printf '%s+release.%s\n' "$VERSION" "${COMPASS_SHA:-unknown}"+ const m = src.match(/printf\s+'([^']*)'\s*\\?\s*\n?\s*"\$VERSION"\s+"\$\{COMPASS_SHA[^}]*\}"/);+ expect(m, "release.yml no longer writes the stamp with a recognisable printf").toBeTruthy();+ return m![1]!.replace(/\\n/g, "\n").replace("%s", SAMPLE_VERSION).replace("%s", SAMPLE_SHA);+ },+ },+ {+ name: "install.sh",+ file: "scripts/install/install.sh",+ render: (src) => {+ // printf '%s+release\n' "$VERSION" > ".../compass/.version"+ const m = src.match(/printf\s+'([^']*)'\s+"\$VERSION"\s*>\s*"[^"]*compass\/\.version"/);+ expect(m, "install.sh no longer writes the stamp with a recognisable printf").toBeTruthy();+ return m![1]!.replace(/\\n/g, "\n").replace("%s", SAMPLE_VERSION);+ },+ },+ {+ name: "install.ps1",+ file: "scripts/install/install.ps1",+ render: (src) => {+ // [System.IO.File]::WriteAllText($CompassStamp, "$Version+release`n")+ const m = src.match(/WriteAllText\(\$CompassStamp,\s*"([^"]*)"\)/);+ expect(m, "install.ps1 no longer writes the stamp with a recognisable WriteAllText").toBeTruthy();+ // PowerShell escapes: backtick-n is a newline; $Version interpolates.+ return m![1]!.replace(/`n/g, "\n").replace("$Version", SAMPLE_VERSION);+ },+ },+ ];++ for (const { name, file, render } of cases) {+ it(`${name} writes a stamp the reader classifies as release`, () => {+ const stamp = render(read(file));+ expect(parseCompassStamp(stamp)).toEqual({ source: "release", version: SAMPLE_VERSION });+ });++ it(`${name} writes exactly one line`, () => {+ const stamp = render(read(file));+ // A trailing newline is fine; an interior one is the regression.+ expect(stamp.trimEnd()).not.toContain("\n");++ // And the property that actually protects old CLIs: their whole-file read+ // must still compare as the Ix version, never as 0.+ const asShippedCliReadsIt = stamp.trim();+ expect(asShippedCliReadsIt.split("+")[0]).toBe(SAMPLE_VERSION);+ });+ }+});diff --git a/ix-cli/src/cli/__tests__/upgrade-compass-stamp.test.ts b/ix-cli/src/cli/__tests__/upgrade-compass-stamp.test.tsnew file mode 100644index 00000000..81348ae2--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-compass-stamp.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vitest";++import { isNewer, parseCompassStamp, shouldOfferCompassUpgradeFor } from "../commands/upgrade.js";++/**+ * Ix#376. `compass/.version` is written by two producers in two unrelated+ * version series — the release workflow stamps the *Ix* version, install.sh and+ * the compass-upgrade path stamp the *ix-compass-dist* release — and the stamp+ * used to record no way to tell them apart. `isNewer(distLatest, stamp)` then+ * compared across series and was correct only while Ix's numbers happened to be+ * the larger ones.+ */+describe("parseCompassStamp", () => {+ it("reads the release form", () => {+ expect(parseCompassStamp("0.9.3+release.7f98724\n")).toEqual({+ source: "release",+ version: "0.9.3",+ });+ // install.sh/install.ps1 have no commit to record, so they write the marker+ // without one.+ expect(parseCompassStamp("0.9.3+release\n")).toEqual({+ source: "release",+ version: "0.9.3",+ });+ });++ it("reads a bare number as dist-series", () => {+ // Both the legacy stamp (everything up to v0.9.2, where install.sh wrote the+ // dist release — the majority of installs in the wild) and the dist form+ // going forward. Reading it as dist keeps those exactly as correct as they+ // already were, and needs no marker.+ expect(parseCompassStamp("0.3.0")).toEqual({ source: "dist", version: "0.3.0" });+ expect(parseCompassStamp(" 0.2.0\n")).toEqual({ source: "dist", version: "0.2.0" });+ });++ it("treats build metadata that is not `release` as dist", () => {+ expect(parseCompassStamp("0.3.0+dist")).toEqual({ source: "dist", version: "0.3.0" });+ expect(parseCompassStamp("0.3.0+abc123")).toEqual({ source: "dist", version: "0.3.0" });+ });++ it("treats an empty or unparseable stamp as absent", () => {+ expect(parseCompassStamp("")).toEqual({ source: "dist", version: "0.0.0" });+ expect(parseCompassStamp(" \n ")).toEqual({ source: "dist", version: "0.0.0" });+ expect(parseCompassStamp("+release")).toEqual({ source: "dist", version: "0.0.0" });+ });++ it("tolerates CRLF, which is how a Windows bundle arrives", () => {+ expect(parseCompassStamp("0.9.3+release.7f98724\r\n")).toEqual({+ source: "release",+ version: "0.9.3",+ });+ });++ it("reads only the first line, so a stray second one cannot poison the version", () => {+ expect(parseCompassStamp("0.9.3+release.7f98724\ntrailing junk\n")).toEqual({+ source: "release",+ version: "0.9.3",+ });+ });++ /**+ * The numbers `isNewer` was being handed before the marker existed. It says+ * "upgrade", which is how a compass built from system-compass main at Ix+ * release time would have been replaced by an older dist build.+ */+ it("shows what isNewer alone answers across the two series", () => {+ // The moment ix-compass-dist tags anything above the running Ix version.+ expect(isNewer("1.0.0", "0.9.3")).toBe(true);+ });+});++/**+ * `compass/.version` has readers we cannot upgrade. Every already-shipped CLI+ * reads it with `getTrackedVersion` — `readFileSync(...).trim()`, the WHOLE+ * file — and hands that straight to `splitVersion`/`isNewer`. The upgrade+ * sequence puts the new stamp in front of the old reader: `ix upgrade` swaps in+ * the new tree, then the still-running old process continues into its own+ * compass block and reads the file it just installed.+ *+ * A multi-line `key=value` stamp made that blob's major parse as+ * `Number("source=release\nix=1")` = NaN -> 0, so an old CLI saw a 1.x release+ * as [0,0,0] and downloaded ix-compass-dist over the newer bundle — Ix#376+ * reintroduced by the format change itself. These cases pin the property that+ * prevents it: whatever the stamp carries, an old reader must still see a+ * version that compares correctly.+ */+describe("legacy readers survive the stamp format", () => {+ // Verbatim getTrackedVersion from the shipped CLI.+ const legacyRead = (raw: string) => raw.trim() || "0.0.0";++ it("never offers a dist downgrade to an old CLI, at any release number", () => {+ for (const ix of ["0.9.3", "0.9.4", "1.0.0", "1.1.0", "2.5.3"]) {+ const onDisk = legacyRead(`${ix}+release.7f98724\n`);+ expect(isNewer("0.3.0", onDisk)).toBe(false);+ }+ });++ it("keeps the whole stamp on one line", () => {+ // The property the loop above depends on. A second line puts the newline+ // inside splitVersion's input and the major becomes NaN -> 0.+ const stamp = "1.0.0+release.7f98724\n";+ expect(legacyRead(stamp)).not.toContain("\n");++ // What the rejected multi-line form would have done, for contrast.+ const multiline = legacyRead("source=release\nix=1.0.0\ncompass=7f98724\n");+ expect(isNewer("0.3.0", multiline)).toBe(true);+ });++ it("still lets an old CLI upgrade a genuine dist bundle", () => {+ expect(isNewer("0.4.0", legacyRead("0.3.0\n"))).toBe(true);+ });+});++/**+ * The decision itself, which is what #376 actually changes. Asserting on+ * parseCompassStamp alone does not reach it: with these cases absent, deleting+ * the `source === "release"` branch left all 728 tests green while restoring+ * the inversion in full.+ */+describe("shouldOfferCompassUpgradeFor", () => {+ const onDisk = (raw: string) => ({ ...parseCompassStamp(raw), present: true });++ it("never replaces a release bundle with a dist build", () => {+ // The exact inversion. dist has tagged 1.0.0, above the running Ix version,+ // so a bare isNewer() would say yes and downgrade a newer bundled compass.+ expect(shouldOfferCompassUpgradeFor("1.0.0", onDisk("0.9.3+release.7f98724"))).toBe(false);++ // Still no, even for a dist release far ahead — the series never converge.+ expect(shouldOfferCompassUpgradeFor("9.9.9", onDisk("0.9.3+release.7f98724"))).toBe(false);+ });++ it("still compares within the dist series", () => {+ expect(shouldOfferCompassUpgradeFor("0.4.0", onDisk("0.3.0"))).toBe(true);+ expect(shouldOfferCompassUpgradeFor("0.3.0", onDisk("0.3.0"))).toBe(false);+ expect(shouldOfferCompassUpgradeFor("0.2.0", onDisk("0.3.0"))).toBe(false);+ });++ it("keeps the repair path for a missing or gutted bundle", () => {+ // present=false is what installedCompass() reports when index.html is+ // absent. The repair must fire for a *release* bundle too, which is why the+ // present check sits ahead of the source check rather than after it —+ // reversing them breaks `ix view` permanently (#365/#366).+ expect(+ shouldOfferCompassUpgradeFor("0.3.0", { source: "release", version: "0.9.3", present: false }),+ ).toBe(true);+ expect(+ shouldOfferCompassUpgradeFor("0.3.0", { source: "dist", version: "0.3.0", present: false }),+ ).toBe(true);+ });++ it("does not 'repair' a present release bundle whose stamp is damaged", () => {+ // The reason `present` is carried separately instead of being encoded as+ // version 0.0.0: a stamp truncated by a full disk or a kill during the+ // non-atomic write also parses as 0.0.0. The bundle beside it is intact and+ // serving, so replacing it with an older dist build is the #376 downgrade+ // reached through a corrupt file instead of a version comparison.+ expect(+ shouldOfferCompassUpgradeFor("0.3.0", { source: "release", version: "0.0.0", present: true }),+ ).toBe(false);+ });++ it("offers nothing when the dist release is unknown", () => {+ // fetchLatestRelease returned nothing — offline, or the repo moved.+ expect(shouldOfferCompassUpgradeFor(undefined, onDisk("0.3.0"))).toBe(false);+ expect(shouldOfferCompassUpgradeFor("", onDisk("0.3.0"))).toBe(false);+ });++ it("treats a legacy bare stamp as dist-series, as it always was", () => {+ // Everything shipped up to v0.9.2. install.sh wrote the dist number here,+ // which is the majority of installs in the wild.+ expect(shouldOfferCompassUpgradeFor("0.3.0", onDisk("0.2.0"))).toBe(true);+ });+});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex cc281a49..d11d0e91 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -192,8 +192,142 @@ export function isNewer(latest: string, current: string): boolean {* always runs.*/function getInstalledCompassVersion(): string {- if (!existsSync(join(COMPASS_DIR, "index.html"))) return "0.0.0";- return getTrackedVersion(COMPASS_VERSION_FILE);+ return installedCompass().version;+}++/**+ * The installed bundle's stamp, plus whether there is a bundle at all.+ *+ * `present` is carried separately rather than being encoded as version "0.0.0".+ * Overloading the version number conflates two states that need opposite+ * answers: a *missing* bundle must be repaired from dist, while a *present*+ * release bundle whose stamp is unreadable must not be — 0.0.0 is also what+ * `parseCompassStamp` returns for a stamp truncated by a full disk or a kill+ * during the non-atomic write, and repairing that downgrades a working bundle.+ *+ * Returns the whole stamp rather than just the number because the source marker+ * is half the answer, and reading the file once keeps the two from disagreeing.+ */+function installedCompass(): CompassStamp & { present: boolean } {+ const present = existsSync(join(COMPASS_DIR, "index.html"));+ if (!present) return { source: "dist", version: "0.0.0", present };+ return { ...readCompassStamp(), present };+}++/**+ * What `compass/.version` says about the bundle beside it.+ *+ * The stamp is written by two different producers in two different version+ * series, and until now it recorded no way to tell them apart (#376):+ *+ * - the **release** workflow stamps the bundle it ships with the **Ix** version+ * (`0.9.2`), because the bundle is built from system-compass `main` at release+ * time and has no dist release number of its own;+ * - **install.sh** and the compass-upgrade path below stamp the+ * **ix-compass-dist** release they downloaded (`0.3.0`).+ *+ * `isNewer(distLatest, stamp)` is only meaningful for the second. Against the+ * first it compares two unrelated series and is correct purely by accident of+ * Ix's numbers currently being the larger ones: the first ix-compass-dist tag+ * above the running Ix version makes `isNewer` true and replaces a *newer*+ * bundled compass with an older dist build. That is the same class of failure+ * as #365/#366, reached from the other end.+ *+ * So the stamp declares its own provenance, and the comparison only runs where+ * it means something. The provenance rides in **semver build metadata**, on one+ * line, because this file has readers we cannot upgrade:+ *+ * 0.9.3+release.7f98724 a bundle built from system-compass main+ * 0.3.0 an ix-compass-dist download+ *+ * That shape is load-bearing. Every already-shipped CLI reads this file with+ * `getTrackedVersion` — `readFileSync(...).trim()`, the *whole file* — and hands+ * the result straight to `splitVersion`. A multi-line `key=value` stamp makes+ * that return the entire blob, whose major parses as `Number("source=release…")`+ * = NaN → 0; the old CLI then sees a 1.x release as `[0,0,0]` and downloads+ * ix-compass-dist over the newer bundle it just installed — reintroducing #376+ * through the format change itself, on exactly the upgrade that ships the fix.+ * `splitVersion` already drops everything after `+` ("Build metadata (`+sha`)+ * never participates in precedence"), so an old CLI reads `0.9.3+release.7f98724`+ * as `0.9.3` and behaves precisely as it does today.+ *+ * A bare version number is both the legacy stamp (everything up to v0.9.2) and+ * the dist form going forward, read as dist-series either way — which is what+ * install.sh wrote, is the majority of installs in the wild, and leaves those+ * exactly as correct as they are today. Release-bundled legacy stamps stay+ * accidentally-correct until compass-dist passes the Ix version, and no worse+ * than before; new releases carry the marker and are immune.+ */+export type CompassStamp = { source: "release" | "dist"; version: string };++export function parseCompassStamp(raw: string): CompassStamp {+ // First line only. Nothing writes a second one, but a stray trailing line+ // must not turn the version into an unparseable blob — that is the failure+ // this format exists to avoid, and it should not survive in our own reader.+ const text = (raw.split(/\r?\n/)[0] ?? "").trim();+ if (!text) return { source: "dist", version: "0.0.0" };++ const plus = text.indexOf("+");+ if (plus < 0) return { source: "dist", version: text };++ const version = text.slice(0, plus).trim();+ // No version means the stamp tells us nothing, marker or not — don't let a+ // bare `+release` assert provenance it has no version to attach to.+ if (!version) return { source: "dist", version: "0.0.0" };++ const build = text.slice(plus + 1).trim();+ // `release` or `release.<sha>`. Matched on the first dot-separated identifier+ // so the commit stays free to change shape.+ const source = build.split(".")[0] === "release" ? "release" : "dist";+ return { source, version };+}++function readCompassStamp(): CompassStamp {+ try {+ if (!existsSync(COMPASS_VERSION_FILE)) return { source: "dist", version: "0.0.0" };+ return parseCompassStamp(readFileSync(COMPASS_VERSION_FILE, "utf-8"));+ } catch {+ return { source: "dist", version: "0.0.0" };+ }+}++/**+ * Should `ix upgrade` offer to replace the installed compass with the latest+ * ix-compass-dist release?+ *+ * Only when the two numbers are in the same series. A release-bundled compass+ * is never replaced: it was built from system-compass `main` when the CLI was+ * cut, so it is at least as new as any dist release published before it, and a+ * dist release published *after* it arrives with the next Ix release, which+ * bundles `main` again. The dist download stays the **repair** path for a+ * missing or gutted bundle, and `present` — `index.html` on disk — is what+ * decides that, deliberately ahead of the source check so a gutted *release*+ * bundle is still repaired.+ *+ * `present` rather than version "0.0.0": that number is also what+ * `parseCompassStamp` yields for a stamp truncated by a full disk or a kill+ * during the non-atomic write, and a present, perfectly serviceable release+ * bundle must not be "repaired" with an older dist build on the strength of a+ * damaged stamp. An unreadable stamp beside a real bundle falls through to the+ * dist comparison, which is what every shipped CLI already does with it.+ *+ * Takes the stamp as an argument rather than reading it: this decision is the+ * whole point of #376, and with the file read inlined the only thing a test+ * could reach was parseCompassStamp — so deleting the source check left every+ * test passing while the inversion came straight back.+ */+export function shouldOfferCompassUpgradeFor(+ compassLatest: string | undefined,+ installed: CompassStamp & { present: boolean },+): boolean {+ if (!compassLatest) return false;+ if (!installed.present) return true; // missing or gutted — repair.+ if (installed.source === "release") return false;+ return isNewer(compassLatest, installed.version);+}++function shouldOfferCompassUpgrade(compassLatest: string | undefined): boolean {+ return shouldOfferCompassUpgradeFor(compassLatest, installedCompass());}function getTrackedVersion(versionFile: string): string {@@ -797,9 +931,7 @@ export async function checkForUpdate(): Promise<void> {if (cache && Date.now() - cache.checkedAt < 3600_000) {const hasCliUpdate = isNewer(cache.latest, current);- const compassCurrent = getInstalledCompassVersion();- const hasCompassUpdate =- cache.compassLatest && isNewer(cache.compassLatest, compassCurrent);+ const hasCompassUpdate = shouldOfferCompassUpgrade(cache.compassLatest);const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);const hasBackendUpdate =cache.backendLatest && isNewer(cache.backendLatest, backendCurrent);@@ -817,9 +949,7 @@ export async function checkForUpdate(): Promise<void> {if (!latest) return;writeCache(latest, compassLatest ?? undefined, backendLatest ?? undefined);const hasCliUpdate = isNewer(latest, current);- const compassCurrent = getInstalledCompassVersion();- const hasCompassUpdate =- compassLatest && isNewer(compassLatest, compassCurrent);+ const hasCompassUpdate = shouldOfferCompassUpgrade(compassLatest ?? undefined);const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);const hasBackendUpdate =backendLatest && isNewer(backendLatest, backendCurrent);@@ -1156,7 +1286,7 @@ export function registerUpgradeCommand(program: Command): void {// ── Compass upgrade ──────────────────────────────────────────────const compassCurrent = getInstalledCompassVersion();- if (compassLatest && isNewer(compassLatest, compassCurrent)) {+ if (shouldOfferCompassUpgrade(compassLatest ?? undefined)) {console.log(`Compass update available: ${compassCurrent === "0.0.0" ? "none" : compassCurrent} → ${chalk.green(compassLatest)}`);@@ -1197,7 +1327,12 @@ export function registerUpgradeCommand(program: Command): void {// did not get stamped, which is not an extract problem and should// not be reported as one.stage = "stamp";- writeFileSync(COMPASS_VERSION_FILE, compassLatest);+ // A bare dist release number. Dist needs no marker: bare *is* the+ // dist form, it is what every shipped CLI already expects to find+ // here, and this number really is in the ix-compass-dist series —+ // which is the series the next run will compare it against+ // (parseCompassStamp, #376).+ writeFileSync(COMPASS_VERSION_FILE, `${compassLatest}\n`);console.log(`[ok] Compass upgraded to ${compassLatest}`);} catch (err) {console.error(`[!!] Compass ${stage} failed: ${describeExecFailure(err)}`);@@ -1220,6 +1355,12 @@ export function registerUpgradeCommand(program: Command): void {cleanupCompassSwap(COMPASS_DIR, compassStaging, compassBackup);rmSync(compassTmp, { recursive: true, force: true });}+ } else if (compassLatest && readCompassStamp().source === "release") {+ // Not "already latest" — it is a different series. Say what it is, so+ // nobody reads a bundled 0.9.2 as a compass version and files #376 again.+ console.log(+ `[ok] Compass is the build bundled with Ix ${compassCurrent} (ix-compass-dist ${compassLatest} not applied)`+ );} else if (compassLatest) {console.log(`[ok] Compass already on the latest version (${compassCurrent})`);} else {diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index 7a876b17..f997ddd6 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -195,14 +195,10 @@ function Get-BackendLatestVersion {}}-function Get-CompassLatestVersion {- try {- $release = Invoke-RestMethod -Uri "https://api.github.com/repos/$GithubOrg/ix-compass-dist/releases/latest" -ErrorAction Stop- return $release.tag_name -replace '^v', ''- } catch {- return $null- }-}+# Get-CompassLatestVersion was removed with Ix#376: the compass this script+# installs comes from the release tarball, so the latest ix-compass-dist release+# number was never the right thing to stamp it with. `ix upgrade` asks that+# question, at a point where it can also tell which series the bundle is in.# ══════════════════════════════════════════════════════════════════════════════@@ -536,11 +532,32 @@ if ($BackendVer) {# on index.html: stamping a version for a compass that is not on disk is what# made `ix upgrade` skip the repair download and break `ix view` permanently.# The warning below is now a real failure signal, not the normal Windows path.-$CompassVer = Get-CompassLatestVersion+#+# The compass installed here always comes from the release tarball, never from+# ix-compass-dist — so it must be stamped as a *release* bundle. This used to+# write the latest ix-compass-dist release number instead, which mislabelled a+# release bundle as a dist build and clobbered the correct stamp the tarball+# already carried, leaving `ix upgrade` ready to downgrade a newer bundled+# compass to an older dist build (Ix#376). Prefer the tarball's own stamp; only+# write one if the bundle has none (zips up to v0.9.2 predate it).+#+# Unlike install.sh this needs no "did we extract?" guard: there is no+# already-current skip path here, so the compass under cli\ always came from the+# zip this run just unpacked and really is a release bundle.+#+# One line, and semver build metadata rather than key=value — see the note in+# release.yml. Every already-shipped CLI reads this file whole and feeds it to+# splitVersion, so a second line makes the version parse as 0 and hands an old+# CLI a reason to replace this bundle with an older dist build.$CompassDir = Join-Path $IxHome "cli\compass"$CompassIndex = Join-Path $CompassDir "index.html"-if ($CompassVer -and (Test-Path -LiteralPath $CompassIndex)) {- [System.IO.File]::WriteAllText((Join-Path $CompassDir ".version"), $CompassVer)+$CompassStamp = Join-Path $CompassDir ".version"+if (Test-Path -LiteralPath $CompassIndex) {+ $HasStamp = (Test-Path -LiteralPath $CompassStamp) -and `+ ((Get-Item -LiteralPath $CompassStamp).Length -gt 0)+ if (-not $HasStamp) {+ [System.IO.File]::WriteAllText($CompassStamp, "$Version+release`n")+ }} elseif (-not (Test-Path -LiteralPath $CompassIndex)) {Write-Warn "System Compass is not installed at $CompassDir — 'ix view' is unavailable until you run 'ix upgrade', which will fetch it."}diff --git a/scripts/install/install.sh b/scripts/install/install.shindex 0f7192b2..50a7a33c 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -132,10 +132,11 @@ resolve_backend_version() {| sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"v\([^"]*\)".*/\1/p' || true}-resolve_compass_version() {- _fetch "https://api.github.com/repos/${GITHUB_ORG}/ix-compass-dist/releases/latest" 2>/dev/null \- | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"v\([^"]*\)".*/\1/p' || true-}+# resolve_compass_version() was removed with Ix#376: the compass this script+# installs comes from the release tarball, so the latest ix-compass-dist release+# number was never the right thing to stamp it with. Nothing here needs to know+# what dist has published — `ix upgrade` asks that question, at a point where it+# can also tell which series the installed bundle belongs to.# -- Detect platform --@@ -886,6 +887,7 @@ check_installed_version() {# specific release, and every build before #259 did publish darwin-amd64 — so a# pinned rollback is allowed through to the normal download-and-404 handling.SKIP_CLI_INSTALL=0+CLI_EXTRACTED=0if [ "$PLATFORM" = "darwin-amd64" ] && [ -z "${IX_VERSION:-}" ]; thenecho ""warn "Ix does not publish a pre-built CLI for Intel Macs (darwin-amd64)."@@ -919,6 +921,10 @@ if [ "$SKIP_CLI_INSTALL" = "0" ] && [ -x "$IX_BIN/ix" ]; thenfiif [ "$SKIP_CLI_INSTALL" = "0" ] && { [ ! -x "$IX_BIN/ix" ] || [ "$(check_installed_version)" != "$VERSION" ]; }; then+ # Records that the compass now under $IX_HOME/cli came out of THIS release+ # tarball. The stamp block near the end of the script needs to know: it must+ # never label a bundle it did not install (Ix#376).+ CLI_EXTRACTED=1mkdir -p "$INSTALL_DIR"TMP_DIR=$(mktemp -d)@@ -1076,9 +1082,38 @@ BACKEND_VER=$(resolve_backend_version)# Windows path. Keep the -f test on index.html: stamping a version for a# compass that is not on disk is what made `ix upgrade` skip the repair# download and break `ix view` permanently.-COMPASS_VER=$(resolve_compass_version)-if [ -n "$COMPASS_VER" ] && [ -f "$IX_HOME/cli/compass/index.html" ]; then- printf '%s' "$COMPASS_VER" > "$IX_HOME/cli/compass/.version"+#+# The compass installed here always comes from the release tarball, never from+# ix-compass-dist — so it must be stamped as a *release* bundle. This used to+# write the latest ix-compass-dist release number instead, which mislabelled a+# release bundle as a dist build and clobbered the correct stamp the tarball+# already carried. The result was live on real installs: a v0.9.x bundle+# stamped `0.2.0`, against a dist latest of `0.3.0`, so `ix upgrade` reported an+# update and would have *downgraded* the bundle to an older build (Ix#376).+#+# Prefer the stamp the tarball shipped with, which since v0.9.3 carries the+# source commit too. Only write one if the bundle has none — tarballs up to+# v0.9.2 predate the stamp.+#+# Gated on CLI_EXTRACTED, and that gate is the whole correctness argument. This+# block runs even when the CLI install was skipped: the version on disk already+# matched, or SKIP_CLI_INSTALL=1 on darwin-amd64. In that case the compass under+# cli/ is whatever was already there, which can be an *ix-compass-dist* bundle+# left unstamped by an interrupted `ix upgrade` (its stage="stamp" failure+# installs the bundle and then fails to write .version). Stamping that+# `+release` would freeze it: shouldOfferCompassUpgradeFor refuses every future+# dist update for a release bundle, so a genuinely stale compass would never be+# replaced and `ix upgrade` would print a claim about it that is simply untrue.+#+# Nothing is lost by skipping it. When we DID extract, the tarball's own stamp+# has already landed and is authoritative — which is also what repairs an+# install mislabelled by the pre-#376 installer. One line, semver build+# metadata: see the note in release.yml on why this file must stay readable by+# already-shipped CLIs.+if [ -f "$IX_HOME/cli/compass/index.html" ]; then+ if [ "$CLI_EXTRACTED" = "1" ] && [ ! -s "$IX_HOME/cli/compass/.version" ]; then+ printf '%s+release\n' "$VERSION" > "$IX_HOME/cli/compass/.version"+ fielif [ ! -f "$IX_HOME/cli/compass/index.html" ]; thenwarn "System Compass is not installed at $IX_HOME/cli/compass — 'ix view' is unavailable until you run 'ix upgrade', which will fetch it."fi