Python
fix(runtime): let a notarized bundle replace a same-build runtime (#21)
kristinhe1111c891a1fd1dbc
diff --git a/memhub/apps/cli/src/cli.ts b/memhub/apps/cli/src/cli.tsindex de67f80..c6740c8 100644--- a/memhub/apps/cli/src/cli.ts+++ b/memhub/apps/cli/src/cli.ts@@ -81,6 +81,7 @@ import {readMemoryWrite,readScanRoots,removeScanRoot,+ resetOnboarding,submitBackup,submitMemoryWrite,submitScan,@@ -688,6 +689,36 @@ async function runCommand(// `path list` and `adapter list` are read-only: they have no plan to confirm,// so they are answered here rather than falling into the two-phase branch// (which would reject them for having nothing to apply).+ // Back to the cold-start screens on purpose. Deleting the app cannot do this+ // (the completion flag lives with the memories, by design), and deleting the+ // data to get there would cost the user everything they have stored.+ if (named === "onboarding" && arguments_.includes("reset")) {+ if (+ arguments_.filter((item) => item === "--json").length > 1 ||+ arguments_.filter((item) => item !== "--json").join(" ") !==+ "onboarding reset"+ ) {+ return usage();+ }+ const attachment = await attachToRuntime(+ resolveRuntimeCliConfig(environment, process.argv[1]).dataDir,+ );+ if (attachment === null) {+ return runtimeUnavailable(descriptor, asJson);+ }+ const state = await resetOnboarding(attachment);+ if (state === null) {+ return reject(descriptor, asJson, "引导状态端点不可用。");+ }+ if (asJson) {+ process.stdout.write(`${JSON.stringify(state)}\n`);+ return EXIT_OK;+ }+ process.stdout.write(+ `引导流程已回到首次运行(status=${state.status}),记忆数据未改动。\n`,+ );+ return EXIT_OK;+ }if (named === "path" && arguments_.includes("list")) {if (arguments_.filter((item) => item === "--json").length > 1 ||diff --git a/memhub/apps/cli/src/command-catalog.ts b/memhub/apps/cli/src/command-catalog.tsindex f2888ff..670d0b2 100644--- a/memhub/apps/cli/src/command-catalog.ts+++ b/memhub/apps/cli/src/command-catalog.ts@@ -651,6 +651,14 @@ export const COMMANDS: readonly CommandDescriptor[] = [],exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_PLAN_BLOCKED],},+ {+ name: "onboarding",+ summary:+ "onboarding reset 回到首次运行的引导流程。只清除引导完成状态:不删记忆数据,也不需要卸载重装。",+ usage: "memhub onboarding reset [--json]",+ options: [JSON_OPTION],+ exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE],+ },{name: "help",summary: "显示总帮助或单个命令的用法。",diff --git a/memhub/apps/cli/src/command-contract.test.ts b/memhub/apps/cli/src/command-contract.test.tsindex fcdfca9..c5b757f 100644--- a/memhub/apps/cli/src/command-contract.test.ts+++ b/memhub/apps/cli/src/command-contract.test.ts@@ -92,6 +92,7 @@ const COMMANDS = ["uninstall","upgrade","delete-data",+ "onboarding","help","version",// A6 product commands. Appended, not inserted: the catalog is a stablediff --git a/memhub/apps/cli/src/core-client.ts b/memhub/apps/cli/src/core-client.tsindex 26542c0..e821c90 100644--- a/memhub/apps/cli/src/core-client.ts+++ b/memhub/apps/cli/src/core-client.ts@@ -397,6 +397,41 @@ export async function readMemoryWrite(}}+export interface OnboardingState {+ status: string;+ selected_source_ids: string[];+ started_at: string | null;+ completed_at: string | null;+}++/** Send onboarding back to its first-run state.+ *+ * Returns null when the endpoint is not there, so an older runtime degrades to+ * "not available" instead of failing the command. Only the completion flag+ * moves: memories, sources and settings live in other tables, which is what+ * makes this the honest way to see the cold-start screens again.+ */+export async function resetOnboarding(+ attachment: RuntimeAttachmentLike,+): Promise<OnboardingState | null> {+ try {+ const response = await axios.post<OnboardingState>(+ `${baseUrlOf(attachment)}/api/v1/onboarding/reset`,+ undefined,+ {+ headers: { Authorization: `Bearer ${attachment.apiToken}` },+ timeout: 15_000,+ proxy: false,+ maxRedirects: 0,+ maxContentLength: MAX_RESPONSE_BYTES,+ },+ );+ return response.data;+ } catch {+ return null;+ }+}+export async function readScanRoots(attachment: RuntimeAttachmentLike,): Promise<{diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.pyindex bc16b7d..38b3eb3 100644--- a/memhub/apps/core/src/one_memory/api.py+++ b/memhub/apps/core/src/one_memory/api.py@@ -1886,6 +1886,20 @@ def create_app("""Record UI completion only; finishing or skipping is never model consent."""return await asyncio.to_thread(_onboarding_store(app).complete)+ @app.post(+ "/api/v1/onboarding/reset",+ response_model=OnboardingState,+ dependencies=protected,+ )+ async def reset_onboarding() -> OnboardingState:+ """Go back to the first-run screens. Only the completion flag moves.++ Memories, sources and settings live in other tables and are untouched,+ which is the point: someone who wants to see the cold-start flow again+ should not have to delete anything to do it.+ """+ return await asyncio.to_thread(_onboarding_store(app).reset)+@app.get("/api/v1/sources",response_model=list[SourceResponse],diff --git a/memhub/apps/core/src/one_memory/onboarding.py b/memhub/apps/core/src/one_memory/onboarding.pyindex 19830d9..c83d90a 100644--- a/memhub/apps/core/src/one_memory/onboarding.py+++ b/memhub/apps/core/src/one_memory/onboarding.py@@ -68,6 +68,16 @@ COMPLETE_INSERT_MYSQL = ("singleton, status, selected_source_ids_json, started_at, completed_at, updated_at"") VALUES (1, 'completed', '[]', NULL, %s, %s)")+RESET_UPDATE_SQLITE = (+ "UPDATE onboarding_state SET status = 'not_started', "+ "selected_source_ids_json = '[]', started_at = NULL, completed_at = NULL, "+ "updated_at = ? WHERE singleton = 1"+)+RESET_UPDATE_MYSQL = (+ "UPDATE onboarding_state SET status = 'not_started', "+ "selected_source_ids_json = '[]', started_at = NULL, completed_at = NULL, "+ "updated_at = %s WHERE singleton = 1"+)class OnboardingState(BaseModel):@@ -140,6 +150,30 @@ class OnboardingStore:)return self.get()+ def reset(self) -> OnboardingState:+ """Return onboarding to its first-run state, touching nothing else.++ The completion flag is stored beside the memories on purpose: a fresh+ install of the app must not greet someone who already has memories as a+ first-time user. That makes the way back to the cold-start screens an+ explicit action rather than a side effect of reinstalling, and it is+ the whole reason this exists: QA and long-time users need to see those+ screens again without giving up a single memory.++ Sources, memories and settings are separate tables and are not read or+ written here.+ """+ now = datetime.now(UTC).isoformat()+ mysql = is_mysql(self._store)+ with self._connect(writing=True) as connection:+ execute(+ connection,+ mysql,+ RESET_UPDATE_MYSQL if mysql else RESET_UPDATE_SQLITE,+ (now,),+ )+ return self.get()+@contextmanagerdef _connect(self,diff --git a/memhub/apps/core/tests/test_onboarding_profile.py b/memhub/apps/core/tests/test_onboarding_profile.pyindex 99198e4..4593956 100644--- a/memhub/apps/core/tests/test_onboarding_profile.py+++ b/memhub/apps/core/tests/test_onboarding_profile.py@@ -13,6 +13,7 @@ basic info 那半边留在 Kuzu 里,本地看不见。"""import asyncio+import sqlite3from httpx import ASGITransport, AsyncClientfrom pydantic import SecretStr@@ -296,6 +297,69 @@ def test_finishing_onboarding_is_not_model_content_consent(tmp_path) -> None:asyncio.run(scenario())+def test_the_way_back_to_the_first_run_deletes_nothing(tmp_path) -> None:+ """重置只动完成标记,记忆一条不少。++ 完成态和记忆放在同一个库里是有意的:重装一遍 App 不该把一个已经有记忆的人+ 当成新用户。代价是想再看一次冷启动,重装不管用。这条盯着那个出口:+ 状态回到首次运行,别的都不动。+ """++ async def scenario() -> None:+ app = _app(tmp_path)+ async with app.router.lifespan_context(app), _client(app) as client:+ database = tmp_path / "data" / "one-memory.sqlite3"+ with sqlite3.connect(database) as connection:+ connection.execute(+ "INSERT INTO governed_memories "+ "(memory_id,user_id,kind,status,content,scopes_json,"+ "revision,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?)",+ (+ "keep-me",+ "local",+ "chat",+ "confirmed",+ "记忆必须保留",+ '["all-apps"]',+ 1,+ "2026-10-17T00:00:00+00:00",+ "2026-10-17T00:00:00+00:00",+ ),+ )+ finished = await client.post("/api/v1/onboarding/complete")++ assert finished.json()["status"] == "completed"++ reset = await client.post("/api/v1/onboarding/reset")++ assert reset.status_code == 200+ assert reset.json()["status"] == "not_started"+ assert reset.json()["completed_at"] is None+ # 落盘了,不是只在响应里改一下:下一次启动读到的也是首次运行。+ assert (await client.get("/api/v1/onboarding")).json()["status"] == "not_started"+ with sqlite3.connect(database) as connection:+ assert connection.execute(+ "SELECT content,revision FROM governed_memories "+ "WHERE memory_id='keep-me'"+ ).fetchone() == ("记忆必须保留", 1)++ asyncio.run(scenario())+++def test_resetting_before_anything_was_completed_is_not_an_error(tmp_path) -> None:+ """绿对照:新库里还没有那一行,重置不能炸。"""++ async def scenario() -> None:+ app = _app(tmp_path)+ async with app.router.lifespan_context(app), _client(app) as client:+ reset = await client.post("/api/v1/onboarding/reset")++ assert reset.status_code == 200+ assert reset.json()["status"] == "not_started"++ asyncio.run(scenario())++def test_hy_being_down_does_not_leave_the_first_install_unfinished(tmp_path) -> None:"""守卫:这一步可跳过,归纳失败不能把引导卡住。diff --git a/memhub/apps/desktop/src/early-startup-errors.ts b/memhub/apps/desktop/src/early-startup-errors.tsindex 48d8873..390654c 100644--- a/memhub/apps/desktop/src/early-startup-errors.ts+++ b/memhub/apps/desktop/src/early-startup-errors.ts@@ -3,6 +3,7 @@ import {diagnosticError,writeDiagnosticEventSync,} from "@one-memory/runtime-control";+import { stableRuntimeUserMessage } from "./stable-runtime";interface EarlyStartupErrorHandlerOptions {processEvents: Pick<EventEmitter, "on" | "removeListener">;@@ -52,7 +53,10 @@ export function installEarlyStartupErrorHandler();options.afterDiagnosticWrite?.();} finally {- options.showError("MemHub 无法启动", errorCode);+ // The dialog is the only part of this a person ever reads, so it gets the+ // explanation, not the code. The code stays in the diagnostic event,+ // where support can still match it against a known failure.+ options.showError("MemHub 无法启动", stableRuntimeUserMessage(error));options.exit(1);}};diff --git a/memhub/apps/desktop/src/main.ts b/memhub/apps/desktop/src/main.tsindex 8147047..8db9290 100644--- a/memhub/apps/desktop/src/main.ts+++ b/memhub/apps/desktop/src/main.ts@@ -1004,6 +1004,9 @@ async function initialize(isQuitting: () => boolean): Promise<void> {...(packagedCommit === undefined? {}: { gitCommit: packagedCommit }),+ // Only the packaged Desktop path opts into a valid same-build,+ // different-commit takeover. CLI installs remain strict.+ replaceSameBuild: true,serviceEnableMarker: runtimeServiceEnableMarkerPath(dataDir),});runtimeChanged = !installed.reused_current;@@ -1165,6 +1168,9 @@ async function initialize(isQuitting: () => boolean): Promise<void> {if (process.platform !== "darwin" && process.platform !== "linux") {throw new Error("packaged_runtime_platform_unsupported");}+ // Captured here, not at the call site: the install callback below is+ // a nested function, and TypeScript drops property narrowing there.+ const hostPlatform = process.platform;const installRoot = defaultManagedInstallRoot(process.platform,app.getPath("home"),@@ -1174,7 +1180,7 @@ async function initialize(isQuitting: () => boolean): Promise<void> {resourcesPath: process.resourcesPath,executablePath: process.execPath,installRoot,- platform: process.platform,+ platform: hostPlatform,arch: process.arch,...(packagedBuildNumber === undefined? {}@@ -1182,6 +1188,7 @@ async function initialize(isQuitting: () => boolean): Promise<void> {...(packagedCommit === undefined? {}: { gitCommit: packagedCommit }),+ replaceSameBuild: true,serviceEnableMarker: runtimeServiceEnableMarkerPath(dataDir),});await installBundledCliIfNeeded({diff --git a/memhub/apps/desktop/src/stable-runtime.test.ts b/memhub/apps/desktop/src/stable-runtime.test.tsindex d87834b..206873f 100644--- a/memhub/apps/desktop/src/stable-runtime.test.ts+++ b/memhub/apps/desktop/src/stable-runtime.test.ts@@ -16,6 +16,7 @@ import {isDisabledServiceInstallError,isInstalledApplicationsApp,stableRuntimeErrorCode,+ stableRuntimeUserMessage,startStableRuntimeRepair,} from "./stable-runtime";@@ -254,3 +255,23 @@ describe("installServiceWithDisabledFallback", () => {expect(startTransient).not.toHaveBeenCalled();});});++describe("startup install errors", () => {+ it("explains the failure to the user instead of showing an error code", () => {+ const conflict = stableRuntimeUserMessage(+ new Error("installed_version_conflict"),+ );+ expect(conflict).toContain("记忆数据");+ expect(conflict).not.toContain("installed_version_conflict");+ expect(+ stableRuntimeUserMessage(new Error("distribution_downgrade_refused")),+ ).toContain("更新");+ // An unrecognised failure still gets a sentence, never a raw code.+ expect(+ stableRuntimeUserMessage(new Error("something_unexpected")),+ ).toContain("MemHub 启动失败");+ expect(stableRuntimeUserMessage("not an error")).toContain(+ "MemHub 启动失败",+ );+ });+});diff --git a/memhub/apps/desktop/src/stable-runtime.ts b/memhub/apps/desktop/src/stable-runtime.tsindex 45a896a..1fedd10 100644--- a/memhub/apps/desktop/src/stable-runtime.ts+++ b/memhub/apps/desktop/src/stable-runtime.ts@@ -178,3 +178,28 @@ export async function installServiceWithDisabledFallback(options: {return "transient";}}++/** What the user is told, instead of an internal error code.+ *+ * The codes are contractual and stay in the logs; this is the layer that turns+ * them into something a person can act on. Every string says what happens to+ * their memories, because that is the first thing anyone asks. */+export const STABLE_RUNTIME_USER_MESSAGES: Record<string, string> = {+ installed_version_conflict:+ "运行环境与这个安装包不一致,无法安全接管。请安装更新版本的 MemHub;你的记忆数据不会受到影响。",+ distribution_downgrade_refused:+ "已安装的运行环境比这个安装包更新,无法用旧安装包启动。请安装最新版本的 MemHub;你的记忆数据不会受到影响。",+ install_current_unmanaged:+ "运行环境的安装目录被改动过,无法安全接管。请重新安装 MemHub,你的记忆数据不会受到影响。",+ desktop_start_failed:+ "MemHub 启动失败。请重新启动;如果仍然打不开,请重新安装,你的记忆数据不会受到影响。",+};++export function stableRuntimeUserMessage(error: unknown): string {+ const code = stableRuntimeErrorCode(error);+ return (+ STABLE_RUNTIME_USER_MESSAGES[code] ??+ STABLE_RUNTIME_USER_MESSAGES.desktop_start_failed ??+ ""+ );+}diff --git a/memhub/packages/runtime-control/src/local-install.test.ts b/memhub/packages/runtime-control/src/local-install.test.tsindex cb9b5ad..1b0476e 100644--- a/memhub/packages/runtime-control/src/local-install.test.ts+++ b/memhub/packages/runtime-control/src/local-install.test.ts@@ -61,7 +61,12 @@ function macho(cpuArch: string): Buffer {async function distribution(version = "1.0.0",- options: { buildNumber?: number; arch?: string; nativeArch?: string } = {},+ options: {+ buildNumber?: number;+ arch?: string;+ nativeArch?: string;+ gitCommit?: string;+ } = {},) {const root = await mkdtemp(path.join(tmpdir(), "one-memory-local-install-"));roots.push(root);@@ -106,6 +111,7 @@ async function distribution(// Derive a monotonic default from the fixture version so an "upgrade"// to 2.0.0 outranks 1.0.0 unless a test overrides it explicitly.(Number.parseInt(version.split(".")[0] ?? "1", 10) || 1),+ git_commit: options.gitCommit ?? null,platform,arch,files: digests,@@ -618,6 +624,187 @@ describe("local Runtime installation", () => {).rejects.toThrow("installed_version_conflict");});+ it("replaces an equal build_number whose bytes differ only when the caller opts in", async () => {+ if (process.platform !== "darwin") return;+ const first = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "a".repeat(40),+ });+ const firstPlan = await planLocalInstall({+ source: first.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ });+ await applyLocalInstall(firstPlan);++ // The same release rebuilt from a new commit: identical build number,+ // different bytes. This is what a re-cut MemHub package looks like.+ const rebuilt = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "b".repeat(40),+ });+ await writeFile(path.join(rebuilt.source, "web/index.html"), "rebuilt web");+ const manifestPath = path.join(rebuilt.source, "manifest.json");+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));+ manifest.files["web/index.html"] = createHash("sha256")+ .update("rebuilt web")+ .digest("hex");+ await writeFile(manifestPath, JSON.stringify(manifest));++ const plan = await planLocalInstall({+ source: rebuilt.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ allowSameBuildReplace: true,+ });+ // The replacement lands in its own directory, so the superseded tree is+ // left intact as a rollback instead of being edited under a running host.+ expect(plan.same_build_replace).toBe(true);+ expect(plan.version_directory).not.toBe(firstPlan.version_directory);++ await applyLocalInstall(plan);+ expect(await readlink(path.join(first.installRoot, "current"))).toBe(+ path.relative(first.installRoot, plan.version_directory),+ );+ expect(+ await readFile(+ path.join(plan.version_directory, "web/index.html"),+ "utf8",+ ),+ ).toBe("rebuilt web");+ expect(+ await readFile(+ path.join(firstPlan.version_directory, "web/index.html"),+ "utf8",+ ),+ ).toBe("web");+ });++ it("uses different directories for different commits with identical payload files", async () => {+ if (process.platform !== "darwin") return;+ const first = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "a".repeat(40),+ });+ const firstPlan = await planLocalInstall({+ source: first.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ });+ await applyLocalInstall(firstPlan);+ const rebuilt = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "b".repeat(40),+ });+ const replacement = await planLocalInstall({+ source: rebuilt.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ allowSameBuildReplace: true,+ });++ expect(replacement.same_build_replace).toBe(true);+ expect(replacement.version_directory).not.toBe(firstPlan.version_directory);+ });++ it("refuses different bytes from the same commit even with the opt-in", async () => {+ if (process.platform !== "darwin") return;+ const commit = "a".repeat(40);+ const first = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: commit,+ });+ await applyLocalInstall(+ await planLocalInstall({+ source: first.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ }),+ );+ const rebuilt = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: commit,+ });+ await writeFile(path.join(rebuilt.source, "web/index.html"), "different");+ const manifestPath = path.join(rebuilt.source, "manifest.json");+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));+ manifest.files["web/index.html"] = createHash("sha256")+ .update("different")+ .digest("hex");+ await writeFile(manifestPath, JSON.stringify(manifest));++ await expect(+ planLocalInstall({+ source: rebuilt.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ allowSameBuildReplace: true,+ }),+ ).rejects.toThrow("installed_version_conflict");+ });++ it("refuses a tampered selected runtime instead of taking it over", async () => {+ if (process.platform !== "darwin") return;+ const first = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "a".repeat(40),+ });+ const firstPlan = await planLocalInstall({+ source: first.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ });+ await applyLocalInstall(firstPlan);+ await writeFile(+ path.join(firstPlan.version_directory, "web/index.html"),+ "tampered",+ );+ const rebuilt = await distribution("1.0.0", {+ buildNumber: 5,+ gitCommit: "b".repeat(40),+ });++ await expect(+ planLocalInstall({+ source: rebuilt.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ allowSameBuildReplace: true,+ }),+ ).rejects.toThrow("distribution_hash_mismatch");+ });++ it("does not let the same-build opt-in weaken downgrade refusal", async () => {+ if (process.platform !== "darwin") return;+ const first = await distribution("1.0.0", { buildNumber: 5 });+ await applyLocalInstall(+ await planLocalInstall({+ source: first.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ }),+ );+ const older = await distribution("0.9.0", { buildNumber: 4 });+ await expect(+ planLocalInstall({+ source: older.source,+ installRoot: first.installRoot,+ platform: process.platform,+ arch: process.arch,+ allowSameBuildReplace: true,+ }),+ ).rejects.toThrow("distribution_downgrade_refused");+ });+it("accepts an equal build_number when the bytes are identical (idempotent reinstall)", async () => {if (process.platform !== "darwin") return;const first = await distribution("1.0.0", { buildNumber: 5 });diff --git a/memhub/packages/runtime-control/src/local-install.ts b/memhub/packages/runtime-control/src/local-install.tsindex 2e04b06..02ab73c 100644--- a/memhub/packages/runtime-control/src/local-install.ts+++ b/memhub/packages/runtime-control/src/local-install.ts@@ -50,6 +50,10 @@ export interface LocalInstallPlan {/** Recorded so `applyLocalInstall` re-verifies with the same opt-in the plan* was created under; it does not itself authorize anything. */allow_downgrade: boolean;+ /** True when this plan replaces an equal `build_number` whose bytes differ.+ * The incoming build gets its own version directory and the superseded tree+ * is left in place, so the transition is still reversible. */+ same_build_replace: boolean;require_protocol_compatibility: boolean;platform: DistributionManifest["platform"];arch: string;@@ -69,6 +73,10 @@ export async function planLocalInstall(options: {/** Explicit, per-invocation opt-in required to install a distribution whose* `build_number` is lower than the selected one. Default is refusal. */allowDowngrade?: boolean;+ /** Explicit, per-invocation opt-in required to replace an equal+ * `build_number` whose bytes differ. Default is refusal+ * (`installed_version_conflict`); see `inspectBuildNumberTransition`. */+ allowSameBuildReplace?: boolean;requireProtocolCompatibility?: boolean;}): Promise<LocalInstallPlan> {if (!isPlatform(options.platform))@@ -86,11 +94,12 @@ export async function planLocalInstall(options: {if (options.requireProtocolCompatibility === true) {assertDistributionProtocolCompatibility(manifest);}- await assertBuildNumberTransition({+ const transition = await inspectBuildNumberTransition({installRoot: options.installRoot,incoming: manifest,incomingSource: source,allowDowngrade: options.allowDowngrade === true,+ allowSameBuildReplace: options.allowSameBuildReplace === true,});const files = Object.keys(manifest.files).sort();const installRoot = path.resolve(options.installRoot);@@ -109,11 +118,18 @@ export async function planLocalInstall(options: {schema_version: 1,source,install_root: installRoot,- version_directory: path.join(installRoot, "versions", id),+ version_directory: path.join(+ installRoot,+ "versions",+ transition.sameBuildReplace+ ? `${id}-r${manifestFingerprint(manifest)}`+ : id,+ ),current_link: path.join(installRoot, "current"),version: manifest.version,build_number: manifest.build_number ?? null,allow_downgrade: options.allowDowngrade === true,+ same_build_replace: transition.sameBuildReplace,require_protocol_compatibility:options.requireProtocolCompatibility === true,platform: manifest.platform,@@ -137,6 +153,7 @@ export async function applyLocalInstall(platform: plan.platform,arch: plan.arch,allowDowngrade: plan.allow_downgrade,+ allowSameBuildReplace: plan.same_build_replace,requireProtocolCompatibility: plan.require_protocol_compatibility,});if (@@ -145,6 +162,7 @@ export async function applyLocalInstall(path.resolve(plan.current_link) !== verified.current_link ||plan.version !== verified.version ||plan.build_number !== verified.build_number ||+ plan.same_build_replace !== verified.same_build_replace ||plan.require_protocol_compatibility !==verified.require_protocol_compatibility ||plan.files !== verified.files@@ -316,18 +334,29 @@ export async function rollbackLocalInstall(* selected version directory already contains byte-identical content —* otherwise the install would silently swap an equal-build package, which the* contract classifies as `installed_version_conflict`.+ *+ * `allowSameBuildReplace` is an explicit, per-invocation escape from that last+ * rule, and it is off by default: a silent equal-build swap is precisely what+ * the refusal protects against. It exists for one caller shape — a runtime+ * shipped inside an app bundle that the OS has already signed and notarized.+ * Such a payload is trusted by construction, and refusing it leaves an affected+ * machine with an app that cannot start at all after a same-build re-release.+ * The replacement never edits the selected tree in place: the incoming build+ * lands in its own version directory and `current` moves atomically, so the+ * superseded tree stays available as a rollback.*/-async function assertBuildNumberTransition(options: {+async function inspectBuildNumberTransition(options: {installRoot: string;incoming: DistributionManifest;incomingSource: string;allowDowngrade: boolean;-}): Promise<void> {+ allowSameBuildReplace: boolean;+}): Promise<{ sameBuildReplace: boolean }> {const installRoot = path.resolve(options.installRoot);const current = await lstat(path.join(installRoot, "current")).catch(() => null,);- if (!current) return;+ if (!current) return { sameBuildReplace: false };if (!current.isSymbolicLink()) throw new Error("install_current_unmanaged");const target = path.resolve(installRoot,@@ -338,28 +367,89 @@ async function assertBuildNumberTransition(options: {if (relative.startsWith("..") || path.isAbsolute(relative)) {throw new Error("install_current_unmanaged");}- const selected = await readManifest(target).catch(() => null);- if (selected === null) return;+ const selected = options.allowSameBuildReplace+ ? await verifyDistribution(+ target,+ options.incoming.platform,+ options.incoming.arch,+ )+ : await readManifest(target).catch(() => null);+ if (selected === null) return { sameBuildReplace: false };// Pre-contract packages have no `build_number`. Comparing them against an// invented ordinal would either break the hourly chain or manufacture a// downgrade; fall back to the prior exact-version behavior until both sides// are numbered.- if (options.incoming.build_number === undefined) return;- if (selected.build_number === undefined) return;- if (options.incoming.build_number > selected.build_number) return;+ if (options.incoming.build_number === undefined)+ return { sameBuildReplace: false };+ if (selected.build_number === undefined) return { sameBuildReplace: false };+ if (options.incoming.build_number > selected.build_number)+ return { sameBuildReplace: false };if (options.incoming.build_number === selected.build_number) {// Same build: an idempotent reinstall is fine only if the bytes match. The// incoming source is verified, so compare it against the selected tree.try {await verifySameTree(options.incomingSource, target);} catch {- throw new Error("installed_version_conflict");+ if (!options.allowSameBuildReplace) {+ throw new Error("installed_version_conflict");+ }+ if (+ !isReleaseCommit(selected.git_commit) ||+ !isReleaseCommit(options.incoming.git_commit) ||+ selected.git_commit === options.incoming.git_commit+ ) {+ // Same commit with different bytes is not a new build: it is a+ // non-reproducible or corrupted artifact and must stay rejected.+ throw new Error("installed_version_conflict");+ }+ return { sameBuildReplace: true };}- return;+ return { sameBuildReplace: false };}if (!options.allowDowngrade) {throw new Error("distribution_downgrade_refused");}+ return { sameBuildReplace: false };+}++/** Short, stable digest of the complete normalized manifest identity.+ *+ * Two packages of the same `build_number` whose bytes differ must not share a+ * version directory: `applyLocalInstall` compares the staged tree against the+ * directory it is about to occupy and would refuse the replacement before+ * `current` could move. Suffixing the directory with a payload fingerprint+ * keeps the equal-build replacement a plain "install then switch" operation. */+function manifestFingerprint(manifest: DistributionManifest): string {+ const packageId = (+ manifest as DistributionManifest & {+ package_id?: unknown;+ }+ ).package_id;+ const identity = {+ schema_version: manifest.schema_version,+ product: manifest.product,+ version: manifest.version,+ build_number: manifest.build_number ?? null,+ git_commit: manifest.git_commit ?? null,+ runtime_protocol: manifest.runtime_protocol ?? null,+ supported_cli_protocol: manifest.supported_cli_protocol ?? null,+ platform: manifest.platform,+ arch: manifest.arch,+ package_id: typeof packageId === "string" ? packageId : null,+ files: Object.fromEntries(+ Object.entries(manifest.files).sort(([left], [right]) =>+ left.localeCompare(right),+ ),+ ),+ };+ return createHash("sha256")+ .update(JSON.stringify(identity))+ .digest("hex")+ .slice(0, 16);+}++function isReleaseCommit(value: string | null | undefined): value is string {+ return typeof value === "string" && /^[0-9a-f]{40}$/.test(value);}async function assertPrivateDirectory(target: string): Promise<void> {diff --git a/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts b/memhub/packages/runtime-control/src/packaged-runtime-install.test.tsindex 815a897..daf275e 100644--- a/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts+++ b/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts@@ -100,6 +100,7 @@ async function installFormalCurrent(options: {executable: string;installRoot: string;buildNumber?: number;+ gitCommit?: string;}): Promise<{ current: string; selected: string }> {const buildNumber = options.buildNumber ?? 3757;const appLayout = await installPackagedRuntime({@@ -109,6 +110,7 @@ async function installFormalCurrent(options: {platform: "darwin",arch: "arm64",buildNumber,+ gitCommit: options.gitCommit ?? "a".repeat(40),});const formalSource = path.join(options.root, `formal-dist-${buildNumber}`);await cp(appLayout.version_directory, formalSource, { recursive: true });@@ -376,6 +378,72 @@ describe("installPackagedRuntime", () => {expect((await lstat(current)).ino).toBe(inodeBefore);});+ it("takes over from a same-build runtime whose bytes differ when the bundle asks it to", async () => {+ const { root, resources, executable, installRoot } = await fixture();+ const { current, selected } = await installFormalCurrent({+ root,+ resources,+ executable,+ installRoot,+ });+ // A re-cut package: same build number, manifest still self-consistent,+ // but not the bytes this bundle carries.+ await writeFile(path.join(selected, "web", "index.html"), "rebuilt-body");+ await rewriteManifestDigest(selected, "web/index.html");+ const receipt = await installPackagedRuntime({+ resourcesPath: resources,+ executablePath: executable,+ installRoot,+ platform: "darwin",+ arch: "arm64",+ buildNumber: 3757,+ gitCommit: "b".repeat(40),+ replaceSameBuild: true,+ });+ expect(receipt.reused_current).toBe(false);+ expect(receipt.version_directory).not.toBe(selected);+ // `current` serves the payload this bundle brought.+ expect(await readlink(current)).toBe(+ path.relative(installRoot, receipt.version_directory),+ );+ expect(+ await readFile(+ path.join(receipt.version_directory, "web", "index.html"),+ "utf8",+ ),+ ).toBe("web-body");+ // The superseded tree is left on disk, not edited: it is the rollback.+ expect(+ await readFile(path.join(selected, "web", "index.html"), "utf8"),+ ).toBe("rebuilt-body");+ });++ it("refuses same-commit different bytes even when the bundle opts in", async () => {+ const { root, resources, executable, installRoot } = await fixture();+ const { selected } = await installFormalCurrent({+ root,+ resources,+ executable,+ installRoot,+ gitCommit: "a".repeat(40),+ });+ await writeFile(path.join(selected, "web", "index.html"), "unexpected");+ await rewriteManifestDigest(selected, "web/index.html");++ await expect(+ installPackagedRuntime({+ resourcesPath: resources,+ executablePath: executable,+ installRoot,+ platform: "darwin",+ arch: "arm64",+ buildNumber: 3757,+ gitCommit: "a".repeat(40),+ replaceSameBuild: true,+ }),+ ).rejects.toThrow("installed_version_conflict");+ });+it.each(["missing"])("refuses a same-build current whose bin/node is %s",async (state) => {diff --git a/memhub/packages/runtime-control/src/packaged-runtime-install.ts b/memhub/packages/runtime-control/src/packaged-runtime-install.tsindex db835f0..ae8f81d 100644--- a/memhub/packages/runtime-control/src/packaged-runtime-install.ts+++ b/memhub/packages/runtime-control/src/packaged-runtime-install.ts@@ -51,6 +51,16 @@ export async function installPackagedRuntime(options: {* CLI-installed distribution. Callers that do know the bundle's build number* must pass it (see `docs/contracts/c0-anti-downgrade-versioning.md`). */buildNumber?: number;+ /** Allow the bundle to take over from an already-selected runtime that+ * reports this same `build_number` but different bytes.+ *+ * Off by default, which preserves `installed_version_conflict`. Desktop turns+ * it on: the bundle it carries has passed notarization, so its payload is+ * already trusted, and the same build number is re-released whenever a+ * release is rebuilt from a new commit. Refusing that case leaves an affected+ * machine with an app that exits on every launch, which is a worse outcome+ * than replacing the runtime. The superseded tree is kept, not edited. */+ replaceSameBuild?: boolean;gitCommit?: string;/** App-owned services use this marker to stop launchd before the App binary* is invoked after the bundle has been removed. */@@ -150,6 +160,7 @@ export async function installPackagedRuntime(options: {platform: options.platform,arch: options.arch,buildNumber: options.buildNumber,+ replaceSameBuild: options.replaceSameBuild === true,executablePath: executable,serviceEnableMarker: options.serviceEnableMarker,});@@ -159,6 +170,7 @@ export async function installPackagedRuntime(options: {installRoot: options.installRoot,platform: options.platform,arch: options.arch,+ allowSameBuildReplace: options.replaceSameBuild === true,requireProtocolCompatibility: true,});return Object.freeze({@@ -176,6 +188,7 @@ async function reuseSelectedSameBuild(options: {platform: "darwin" | "linux";arch: string;buildNumber: number | undefined;+ replaceSameBuild: boolean;executablePath: string;serviceEnableMarker: string | undefined;}): Promise<PackagedRuntimeInstallReceipt | null> {@@ -239,11 +252,15 @@ async function reuseSelectedSameBuild(options: {): null;if (selectedDigest !== digest && selectedDigest !== formalDigest) {+ // Same build number, different bytes: not reusable. Hand the install+ // back to the normal path so the bundle lands in its own directory.+ if (options.replaceSameBuild) return null;throw new Error("installed_version_conflict");}continue;}if (selectedManifest.files[relative] !== digest) {+ if (options.replaceSameBuild) return null;throw new Error("installed_version_conflict");}}@@ -276,6 +293,8 @@ async function reuseSelectedSameBuild(options: {version: selectedManifest.version,build_number: selectedManifest.build_number ?? null,allow_downgrade: false,+ // Nothing was replaced: the selected tree already matched this bundle.+ same_build_replace: false,require_protocol_compatibility: true,platform: selectedManifest.platform,arch: selectedManifest.arch,