@adea-ai/app-framework 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,326 @@
1
+ import { dirname, isAbsolute, join, resolve } from "node:path";
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, watch, writeFileSync } from "node:fs";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { homedir } from "node:os";
5
+ // src/developer-app/developer-app.ts
6
+ /**
7
+ * The developer app: one persistent, hot-reloading desktop app per framework app that
8
+ * runs straight from the developer's checkout. With GitButler the checkout is every
9
+ * applied branch merged together, so the window always shows the combined state of all
10
+ * parallel work, with no build or publish step. It replaces dev releases: a public app
11
+ * ships only daily and stable.
12
+ *
13
+ * - The UI comes from the app's dev server (Vite), proxied by the shell, so client
14
+ * edits hot-reload in place (see `client-dev-proxy.ts`).
15
+ * - Shell source edits restart the shell process.
16
+ * - It is its own app: "<Name> (Dev)", identifier "<identifier>.live", its own data
17
+ * folder and port, so it runs beside an installed copy of the public app.
18
+ * - `installDeveloperAppLauncher` adds a small launcher app (Spotlight, Launchpad,
19
+ * Dock) that starts it from the checkout.
20
+ */
21
+ /** Set for every developer app build and run; the build hook and the shell read it. */
22
+ var DEVELOPER_APP_VARIABLE = "ADEA_DEVELOPER_APP";
23
+ /** The developer app's display name, for the build hook's bundle naming. */
24
+ var DEVELOPER_APP_NAME_VARIABLE = "ADEA_DEVELOPER_APP_NAME";
25
+ var NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,62}$/;
26
+ var IDENTIFIER_PATTERN = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/i;
27
+ var strings = (list) => Array.isArray(list) && list.every((item) => typeof item === "string" && item.length > 0);
28
+ var stringRecord = (map) => map === void 0 || typeof map === "object" && map !== null && !Array.isArray(map) && Object.values(map).every((item) => typeof item === "string");
29
+ /** Check a developer app config, resolving its paths against `base`. */
30
+ function parseDeveloperAppConfig(value, base) {
31
+ const config = value;
32
+ if (!config || typeof config !== "object" || typeof config.name !== "string" || !NAME_PATTERN.test(config.name) || typeof config.identifier !== "string" || !IDENTIFIER_PATTERN.test(config.identifier) || typeof config.shellDirectory !== "string" || config.watch !== void 0 && !strings(config.watch) || !config.ui || typeof config.ui.directory !== "string" || !strings(config.ui.command) || config.ui.command.length === 0 || !Number.isInteger(config.ui.port) || config.ui.port < 1024 || config.ui.port > 65535 || config.ui.warm !== void 0 && (!strings(config.ui.warm) || config.ui.warm.some((path) => !path.startsWith("/"))) || !stringRecord(config.ui.env) || !stringRecord(config.shellEnv) || config.prepare !== void 0 && (!Array.isArray(config.prepare) || config.prepare.some((command) => !strings(command) || command.length === 0)) || config.icon !== void 0 && typeof config.icon !== "string") throw new Error("Invalid developer app configuration");
33
+ const at = (path) => isAbsolute(path) ? path : resolve(base, path);
34
+ const shellDirectory = at(config.shellDirectory);
35
+ return {
36
+ ...config,
37
+ name: config.name,
38
+ identifier: config.identifier,
39
+ shellDirectory,
40
+ ui: {
41
+ ...config.ui,
42
+ directory: at(config.ui.directory)
43
+ },
44
+ ...config.icon === void 0 ? {} : { icon: at(config.icon) }
45
+ };
46
+ }
47
+ /** Read and check a developer app config file (JSON); paths resolve from its folder. */
48
+ function readDeveloperAppConfig(path) {
49
+ return parseDeveloperAppConfig(JSON.parse(readFileSync(path, "utf8")), dirname(resolve(path)));
50
+ }
51
+ /** The developer app's own identity, kept apart from the public app's. */
52
+ function developerAppIdentity(app) {
53
+ return {
54
+ name: `${app.name} (Dev)`,
55
+ identifier: `${app.identifier}.live`,
56
+ buildFolder: "build.noindex",
57
+ icons: "build.noindex/developer-icon.iconset"
58
+ };
59
+ }
60
+ /** Whether this process builds or runs the developer app. */
61
+ var isDeveloperApp = (env = process.env) => env[DEVELOPER_APP_VARIABLE] === "1";
62
+ /**
63
+ * Electrobun names a non-stable bundle `${name}-${channel}.app` and cannot be told
64
+ * otherwise. This moves the bundle to "<Name> (Dev).app" (the name macOS shows in
65
+ * Finder, Activity Monitor and permission prompts) and leaves a relative symlink at the
66
+ * channel path, which `electrobun dev` launches and rebuilds through. Returns the
67
+ * bundle path, or undefined when there is no bundle.
68
+ */
69
+ function nameDeveloperBundle(buildDir, appName, displayName) {
70
+ const bundle = `${displayName}.app`;
71
+ const target = join(buildDir, bundle);
72
+ const built = readdirSync(buildDir).find((entry) => entry !== bundle && entry.startsWith(`${appName}-`) && entry.endsWith(".app"));
73
+ if (!built) return existsSync(target) ? target : void 0;
74
+ const builtPath = join(buildDir, built);
75
+ if (lstatSync(builtPath).isSymbolicLink()) return target;
76
+ rmSync(target, {
77
+ recursive: true,
78
+ force: true
79
+ });
80
+ renameSync(builtPath, target);
81
+ symlinkSync(bundle, builtPath);
82
+ return target;
83
+ }
84
+ /** The build hook's developer app step (macOS): bundle and Info.plist named "<Name> (Dev)". */
85
+ function finishDeveloperBundle(env = process.env) {
86
+ const displayName = env[DEVELOPER_APP_NAME_VARIABLE];
87
+ const buildDir = env.ELECTROBUN_BUILD_DIR;
88
+ const appName = env.ELECTROBUN_APP_NAME;
89
+ if (!isDeveloperApp(env) || process.platform !== "darwin" || !displayName) return void 0;
90
+ if (!buildDir || !appName || !existsSync(buildDir)) return void 0;
91
+ const bundle = nameDeveloperBundle(buildDir, appName, displayName);
92
+ if (!bundle) return void 0;
93
+ const plist = join(bundle, "Contents", "Info.plist");
94
+ if (existsSync(plist)) for (const key of ["CFBundleName", "CFBundleDisplayName"]) spawnSync("plutil", [
95
+ "-replace",
96
+ key,
97
+ "-string",
98
+ displayName,
99
+ plist
100
+ ], { stdio: "ignore" });
101
+ return bundle;
102
+ }
103
+ /**
104
+ * Debounced shell restarts: a shell source edit restarts the running shell. An edit
105
+ * before the shell's first start is ignored, because that start builds current files.
106
+ */
107
+ function createShellRestarter(options) {
108
+ const { currentShell, restart, delayMs = 400, log = () => {} } = options;
109
+ let timer;
110
+ let inFlight = false;
111
+ let pending;
112
+ const run = (file) => {
113
+ const shell = currentShell();
114
+ if (!shell || shell.exitCode !== null) return;
115
+ inFlight = true;
116
+ log(`developer app: ${file} changed, restarting the shell…`);
117
+ restart(shell).catch(() => void 0).finally(() => {
118
+ inFlight = false;
119
+ const next = pending;
120
+ pending = void 0;
121
+ if (next !== void 0) run(next);
122
+ });
123
+ };
124
+ return (file) => {
125
+ if (!file || /\.test\.tsx?$/.test(file)) return;
126
+ clearTimeout(timer);
127
+ timer = setTimeout(() => {
128
+ if (inFlight) pending = file;
129
+ else run(file);
130
+ }, delayMs);
131
+ };
132
+ }
133
+ var ICON_SIZES = [
134
+ 16,
135
+ 32,
136
+ 128,
137
+ 256,
138
+ 512
139
+ ];
140
+ function writeIconset(png, iconset) {
141
+ mkdirSync(iconset, { recursive: true });
142
+ for (const size of ICON_SIZES) for (const [scale, suffix] of [[1, ""], [2, "@2x"]]) {
143
+ const pixels = String(Math.min(size * scale, 512));
144
+ const out = join(iconset, `icon_${size}x${size}${suffix}.png`);
145
+ spawnSync("sips", [
146
+ "-z",
147
+ pixels,
148
+ pixels,
149
+ png,
150
+ "--out",
151
+ out
152
+ ], { stdio: "ignore" });
153
+ }
154
+ }
155
+ /** The shell environment for a developer app run. */
156
+ function developerAppShellEnv(config, env = process.env) {
157
+ return {
158
+ ...env,
159
+ ...config.shellEnv,
160
+ [DEVELOPER_APP_VARIABLE]: "1",
161
+ [DEVELOPER_APP_NAME_VARIABLE]: developerAppIdentity(config).name,
162
+ ADEA_CLIENT_DEV_URL: `http://127.0.0.1:${config.ui.port}`
163
+ };
164
+ }
165
+ /** Stop a child and the process group it leads. */
166
+ function stopGroup(child) {
167
+ try {
168
+ process.kill(-child.pid, "SIGTERM");
169
+ } catch {
170
+ child.kill("SIGTERM");
171
+ }
172
+ }
173
+ /**
174
+ * Run the developer app from the checkout until its window closes or the process is
175
+ * stopped: the UI dev server first, then the shell once the dev server answers.
176
+ */
177
+ async function runDeveloperApp(config, options = {}) {
178
+ const log = options.log ?? ((line) => console.log(line));
179
+ const identity = developerAppIdentity(config);
180
+ for (const command of config.prepare ?? []) {
181
+ const result = spawnSync(command[0], command.slice(1), {
182
+ cwd: config.shellDirectory,
183
+ stdio: "inherit",
184
+ env: {
185
+ ...process.env,
186
+ [DEVELOPER_APP_VARIABLE]: "1"
187
+ }
188
+ });
189
+ if (result.status !== 0) process.exit(result.status ?? 1);
190
+ }
191
+ if (config.icon && process.platform === "darwin") writeIconset(config.icon, join(config.shellDirectory, identity.icons));
192
+ const children = /* @__PURE__ */ new Set();
193
+ const start = (command, spawnOptions) => {
194
+ const child = spawn(command[0], command.slice(1), {
195
+ stdio: "inherit",
196
+ detached: true,
197
+ ...spawnOptions
198
+ });
199
+ children.add(child);
200
+ child.on("exit", () => children.delete(child));
201
+ return child;
202
+ };
203
+ const shutdown = (code) => {
204
+ for (const child of children) stopGroup(child);
205
+ process.exit(code);
206
+ };
207
+ process.on("SIGINT", () => shutdown(0));
208
+ process.on("SIGTERM", () => shutdown(0));
209
+ start(config.ui.command, {
210
+ cwd: config.ui.directory,
211
+ env: {
212
+ ...process.env,
213
+ ...config.ui.env,
214
+ [DEVELOPER_APP_VARIABLE]: "1"
215
+ }
216
+ }).on("exit", (code) => {
217
+ log(`developer app: the UI dev server exited (${code ?? "signal"})`);
218
+ shutdown(code ?? 1);
219
+ });
220
+ const origin = `http://127.0.0.1:${config.ui.port}`;
221
+ log("developer app: starting the UI dev server…");
222
+ for (;;) {
223
+ try {
224
+ if ((await fetch(origin + "/")).status < 500) break;
225
+ } catch {}
226
+ await new Promise((done) => setTimeout(done, 500));
227
+ }
228
+ for (const path of config.ui.warm ?? []) await fetch(origin + path, { signal: AbortSignal.timeout(12e4) }).catch(() => void 0);
229
+ log(`developer app: UI on ${origin} (hot reload); starting ${identity.name}`);
230
+ let shell;
231
+ let restarting = false;
232
+ const shellEnv = developerAppShellEnv(config);
233
+ const startShell = () => {
234
+ shell = start([
235
+ "bunx",
236
+ "--bun",
237
+ "electrobun",
238
+ "dev"
239
+ ], {
240
+ cwd: config.shellDirectory,
241
+ env: shellEnv
242
+ });
243
+ shell.on("exit", (code) => {
244
+ if (restarting) return;
245
+ log(`developer app: the shell exited (${code ?? "signal"})`);
246
+ shutdown(code ?? 0);
247
+ });
248
+ };
249
+ const onChange = createShellRestarter({
250
+ currentShell: () => shell,
251
+ log,
252
+ restart: (running) => new Promise((started) => {
253
+ restarting = true;
254
+ running.once("exit", () => {
255
+ restarting = false;
256
+ startShell();
257
+ started();
258
+ });
259
+ stopGroup(running);
260
+ })
261
+ });
262
+ for (const folder of config.watch ?? ["src"]) watch(join(config.shellDirectory, folder), { recursive: true }, (_event, file) => onChange(file ? String(file) : null));
263
+ startShell();
264
+ return new Promise(() => {});
265
+ }
266
+ var quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
267
+ /**
268
+ * Install the developer app's launcher (macOS): "<Name> (Dev).app" in `directory`
269
+ * (default /Applications), which runs `command` from `checkout` in a login shell, so it
270
+ * finds bun on the same PATH as a terminal. Output goes to ~/Library/Logs/<Name> (Dev).log.
271
+ */
272
+ function installDeveloperAppLauncher(options) {
273
+ if (process.platform !== "darwin") throw new Error("The developer app launcher is macOS-only");
274
+ const identity = developerAppIdentity(options.config);
275
+ const app = join(options.directory ?? "/Applications", `${identity.name}.app`);
276
+ const contents = join(app, "Contents");
277
+ const log = join(homedir(), "Library", "Logs", `${identity.name}.log`);
278
+ const executable = "developer-app";
279
+ rmSync(app, {
280
+ recursive: true,
281
+ force: true
282
+ });
283
+ mkdirSync(join(contents, "MacOS"), { recursive: true });
284
+ mkdirSync(join(contents, "Resources"), { recursive: true });
285
+ const notice = `display notification "Starting from the checkout. The window opens in about a minute." with title "${identity.name.replaceAll("\"", "")}"`;
286
+ writeFileSync(join(contents, "MacOS", executable), `#!/bin/zsh -l
287
+ osascript -e ${quote(notice)} >/dev/null 2>&1 &
288
+ cd ${quote(options.checkout)} || exit 1
289
+ exec ${options.command.map(quote).join(" ")} >> ${quote(log)} 2>&1
290
+ `);
291
+ chmodSync(join(contents, "MacOS", executable), 493);
292
+ writeFileSync(join(contents, "Info.plist"), `<?xml version="1.0" encoding="UTF-8"?>
293
+ <plist version="1.0">
294
+ <dict>
295
+ <key>CFBundleName</key><string>${identity.name}</string>
296
+ <key>CFBundleDisplayName</key><string>${identity.name}</string>
297
+ <key>CFBundleIdentifier</key><string>${identity.identifier}.launcher</string>
298
+ <key>CFBundleExecutable</key><string>${executable}</string>
299
+ <key>CFBundleIconFile</key><string>AppIcon</string>
300
+ <key>CFBundlePackageType</key><string>APPL</string>
301
+ <key>CFBundleVersion</key><string>1</string>
302
+ <key>LSUIElement</key><true/>
303
+ </dict>
304
+ </plist>
305
+ `);
306
+ if (options.config.icon) {
307
+ const iconset = join(contents, "Resources", "AppIcon.iconset");
308
+ writeIconset(options.config.icon, iconset);
309
+ spawnSync("iconutil", [
310
+ "-c",
311
+ "icns",
312
+ iconset,
313
+ "-o",
314
+ join(contents, "Resources", "AppIcon.icns")
315
+ ]);
316
+ rmSync(iconset, {
317
+ recursive: true,
318
+ force: true
319
+ });
320
+ }
321
+ return {
322
+ app,
323
+ log
324
+ };
325
+ }
326
+ export { DEVELOPER_APP_NAME_VARIABLE, DEVELOPER_APP_VARIABLE, createShellRestarter, developerAppIdentity, developerAppShellEnv, finishDeveloperBundle, installDeveloperAppLauncher, isDeveloperApp, nameDeveloperBundle, parseDeveloperAppConfig, readDeveloperAppConfig, runDeveloperApp };
@@ -1 +1 @@
1
- {"version":"0.38.0","commit":"53f877e75ef6345dd53f4a80b06d85244cdcace6"}
1
+ {"version":"0.39.0","commit":"a96af4fbc2012cc05a0fa1cfed906934dfdc7ac5"}
@@ -3,5 +3,7 @@
3
3
  * On Windows it applies the pinned WebView2 runtime correction. On every
4
4
  * platform it replaces bundled CEF helpers with the build that exposes
5
5
  * Electrobun's bridges to the main frame only; bundles without CEF are untouched.
6
+ * For a developer app build (`ADEA_DEVELOPER_APP=1`) it names the macOS bundle
7
+ * "<Name> (Dev)" (see developer-app.ts).
6
8
  */
7
9
  export default function secureDesktopBuild(): Promise<void>;
@@ -1,12 +1,15 @@
1
1
  import { cefHelperFailure, installPatchedCefHelpers } from "./cef-helper.js";
2
2
  import { installOptInPosixLaunchLeaseLauncher } from "./posix-launcher-build.js";
3
3
  import secureWindowsBuild from "./windows-build-hook.js";
4
+ import { finishDeveloperBundle } from "../developer-app/developer-app.js";
4
5
  // src/native/desktop-build-hook.ts
5
6
  /**
6
7
  * Electrobun postBuild hook; runs before release hashing, packaging and signing.
7
8
  * On Windows it applies the pinned WebView2 runtime correction. On every
8
9
  * platform it replaces bundled CEF helpers with the build that exposes
9
10
  * Electrobun's bridges to the main frame only; bundles without CEF are untouched.
11
+ * For a developer app build (`ADEA_DEVELOPER_APP=1`) it names the macOS bundle
12
+ * "<Name> (Dev)" (see developer-app.ts).
10
13
  */
11
14
  async function secureDesktopBuild() {
12
15
  await secureWindowsBuild();
@@ -23,5 +26,7 @@ async function secureDesktopBuild() {
23
26
  } catch {
24
27
  throw new Error("Pinned POSIX launcher preparation failed");
25
28
  }
29
+ const developerBundle = finishDeveloperBundle(process.env);
30
+ if (developerBundle) process.stdout.write(`Named the developer app bundle: ${developerBundle}\n`);
26
31
  }
27
32
  export { secureDesktopBuild as default };
@@ -51,7 +51,7 @@ var workflowFile = (path) => path.slice(18);
51
51
  var workflowPath = (value) => typeof value === "string" && value.length <= 200 && value.startsWith(workflowDirectory) && /^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/.test(workflowFile(value));
52
52
  /** Validate shared daily, dev and stable asset requirements. */
53
53
  function parseReleaseConfig(config) {
54
- if (!isRecord(config) || !isRecord(config.platforms) || !strings(config.releaseAssets) || !strings(config.dailyDiscoveryAssets) || !strings(config.stableDiscoveryAssets) || !strings(config.devDiscoveryAssets) || !Number.isSafeInteger(config.soakHours) || Number(config.soakHours) < 0 || Number(config.soakHours) > 8760) throw new Error("Invalid release configuration");
54
+ if (!isRecord(config) || !isRecord(config.platforms) || !strings(config.releaseAssets) || !strings(config.dailyDiscoveryAssets) || !strings(config.stableDiscoveryAssets) || config.devDiscoveryAssets !== void 0 && !strings(config.devDiscoveryAssets) || !Number.isSafeInteger(config.soakHours) || Number(config.soakHours) < 0 || Number(config.soakHours) > 8760) throw new Error("Invalid release configuration");
55
55
  const workflows = config.releaseWorkflows;
56
56
  let releaseWorkflows;
57
57
  if (workflows !== void 0) {
@@ -98,7 +98,7 @@ function parseReleaseConfig(config) {
98
98
  const releaseAssets = [...config.releaseAssets];
99
99
  const daily = [...config.dailyDiscoveryAssets];
100
100
  const stable = [...config.stableDiscoveryAssets];
101
- const dev = [...config.devDiscoveryAssets];
101
+ const dev = config.devDiscoveryAssets === void 0 ? [] : [...config.devDiscoveryAssets];
102
102
  if (daily.some((name) => !releaseAssets.includes(name) || stable.includes(name) || dev.includes(name)) || stable.some((name) => !releaseAssets.includes(name) || dev.includes(name)) || dev.some((name) => !releaseAssets.includes(name))) throw new Error("Daily, stable and dev discovery assets must be distinct release assets");
103
103
  const requirements = (tag) => {
104
104
  if (!/^v\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(tag) || tag.length > 65) throw new Error("Invalid release tag");
@@ -750,7 +750,8 @@ function sameUpdateTreeIdentity(left, right) {
750
750
  function sameTreeEntrySnapshot(left, right) {
751
751
  return left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.nlink === right.nlink && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
752
752
  }
753
- async function readUpdateTreeDigest(tree) {
753
+ async function readUpdateTreeDigest(tree, options = {}) {
754
+ const allowHardLinkedFiles = options.allowHardLinkedFiles === true;
754
755
  const hash = createHash("sha256");
755
756
  hash.update("adea-framework-update-tree\x00v1\x00", "utf8");
756
757
  const root = await lstat2(tree, { bigint: true });
@@ -802,7 +803,7 @@ async function readUpdateTreeDigest(tree) {
802
803
  throw new Error("Update tree changed while reading a directory");
803
804
  return;
804
805
  }
805
- if (!before.isFile() || before.nlink !== 1n || before.size < 0n)
806
+ if (!before.isFile() || before.nlink < 1n || !allowHardLinkedFiles && before.nlink !== 1n || before.size < 0n)
806
807
  throw new Error("Update tree contains an unsupported filesystem entry");
807
808
  writeRecord("file", relative, before.mode, before.size);
808
809
  const noFollow = constants5.O_NOFOLLOW ?? 0;
@@ -837,6 +838,9 @@ async function readUpdateTreeDigest(tree) {
837
838
  hash.update(count);
838
839
  return hash.digest("hex");
839
840
  }
841
+ function readInstalledUpdateTreeDigest(tree) {
842
+ return readUpdateTreeDigest(tree, { allowHardLinkedFiles: true });
843
+ }
840
844
  function sameUpdateTreeDigest(left, right) {
841
845
  return typeof left === "string" && typeof right === "string" && isSha256Hex(left) && left === right;
842
846
  }
@@ -1686,7 +1690,7 @@ async function runSchema3UpdateHelper(options, request, helperLiveness) {
1686
1690
  await syncUpdateTreeParent(request.target);
1687
1691
  if (await readUpdateTreeVersion(request.target) !== swapping.version || await readUpdateTreeVersion(candidate) !== swapping.previousVersion || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(request.target), swapping.candidateTreeIdentity) || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(candidate), swapping.previousTreeIdentity))
1688
1692
  throw new Error("Atomic update exchange produced unexpected tree versions");
1689
- if (!sameUpdateTreeDigest(await readUpdateTreeDigest(request.target), swapping.candidateTreeDigest))
1693
+ if (!sameUpdateTreeDigest(await readInstalledUpdateTreeDigest(request.target), swapping.candidateTreeDigest))
1690
1694
  throw new Error("Installed update tree content changed during the directory exchange");
1691
1695
  completedDigestVerified = true;
1692
1696
  await writeUpdateStageStateDurably(options.staging, { ...swapping, phase: "completed" });
@@ -3,6 +3,8 @@ import { type UpdateStageState } from '../update-state-store';
3
3
  import type { UpdateResumeResult } from './update-resume';
4
4
  export declare function exists(path: string): Promise<boolean>;
5
5
  export declare function readTreeDigestForProof(path: string): Promise<string | undefined>;
6
+ /** Prove an installed tree, which may gain hard links after the exchange. */
7
+ export declare function readInstalledTreeDigestForProof(path: string): Promise<string | undefined>;
6
8
  /** Recover only layouts produced by a proven-exited legacy helper. */
7
9
  export declare function recoverLegacyHandoff(options: {
8
10
  target: string;
@@ -11,6 +13,7 @@ export declare function recoverLegacyHandoff(options: {
11
13
  helperPid: number;
12
14
  }): Promise<UpdateResumeResult>;
13
15
  export declare function resetToStaged(staging: string, state: UpdateStageState): Promise<UpdateStageState>;
16
+ export declare function hasUnknownStagingEntries(staging: string, allowed?: readonly string[], generation?: string): Promise<boolean>;
14
17
  export declare function reconcileSwap(target: string, staging: string, state: UpdateStageState): Promise<UpdateStageState | undefined>;
15
18
  export declare function recoverStagedCandidate(options: {
16
19
  target: string;
@@ -4,7 +4,7 @@ import { renameExclusive } from "../../native/native-rename.js";
4
4
  import { parseUpdateHelperRequest } from "./update-helper.js";
5
5
  import { updateProcessMayBeAlive } from "../locks/update-process-liveness.js";
6
6
  import { readUpdateHelperRequestFile, writeUpdateStageState } from "../update-state-store.js";
7
- import { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity } from "../install/update-swap.js";
7
+ import { readInstalledUpdateTreeDigest, readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity } from "../install/update-swap.js";
8
8
  import { lstat, readdir, rm } from "node:fs/promises";
9
9
  import { join } from "node:path";
10
10
  import { randomUUID } from "node:crypto";
@@ -32,6 +32,14 @@ async function readTreeDigestForProof(path) {
32
32
  return;
33
33
  }
34
34
  }
35
+ /** Prove an installed tree, which may gain hard links after the exchange. */
36
+ async function readInstalledTreeDigestForProof(path) {
37
+ try {
38
+ return await readInstalledUpdateTreeDigest(path);
39
+ } catch {
40
+ return;
41
+ }
42
+ }
35
43
  /** Recover only layouts produced by a proven-exited legacy helper. */
36
44
  async function recoverLegacyHandoff(options) {
37
45
  const { target, staging, currentVersion, helperPid } = options;
@@ -145,7 +153,7 @@ async function reconcileSwap(target, staging, state) {
145
153
  const [targetVersion, candidateVersion] = await Promise.all([readUpdateTreeVersion(target), readUpdateTreeVersion(candidate)]);
146
154
  const [targetIdentity, candidateIdentity] = await Promise.all([readUpdateTreeIdentity(target), readUpdateTreeIdentity(candidate)]);
147
155
  if (targetVersion === state.previousVersion && candidateVersion === state.version && targetIdentity !== void 0 && candidateIdentity !== void 0 && sameUpdateTreeIdentity(candidateIdentity, state.candidateTreeIdentity) && (state.candidateTreeDigest === void 0 || sameUpdateTreeDigest(await readTreeDigestForProof(candidate), state.candidateTreeDigest)) && !sameUpdateTreeIdentity(targetIdentity, candidateIdentity) && (!state.previousTreeIdentity || sameUpdateTreeIdentity(targetIdentity, state.previousTreeIdentity))) return resetToStaged(staging, state);
148
- if (targetVersion === state.version && candidateVersion === state.previousVersion && sameUpdateTreeIdentity(targetIdentity, state.candidateTreeIdentity) && (state.candidateTreeDigest === void 0 || sameUpdateTreeDigest(await readTreeDigestForProof(target), state.candidateTreeDigest)) && sameUpdateTreeIdentity(candidateIdentity, state.previousTreeIdentity)) {
156
+ if (targetVersion === state.version && candidateVersion === state.previousVersion && sameUpdateTreeIdentity(targetIdentity, state.candidateTreeIdentity) && (state.candidateTreeDigest === void 0 || sameUpdateTreeDigest(await readInstalledTreeDigestForProof(target), state.candidateTreeDigest)) && sameUpdateTreeIdentity(candidateIdentity, state.previousTreeIdentity)) {
149
157
  const completed = {
150
158
  ...state,
151
159
  phase: "completed"
@@ -177,4 +185,4 @@ async function recoverStagedCandidate(options) {
177
185
  channel: verified.descriptor.channel
178
186
  };
179
187
  }
180
- export { exists, readTreeDigestForProof, reconcileSwap, recoverLegacyHandoff, recoverStagedCandidate, resetToStaged };
188
+ export { exists, hasUnknownStagingEntries, readInstalledTreeDigestForProof, readTreeDigestForProof, reconcileSwap, recoverLegacyHandoff, recoverStagedCandidate, resetToStaged };
@@ -2,7 +2,7 @@ import { errorCode, isUuid } from "../../app/value-guards.js";
2
2
  import { publishExclusiveUpdateMarker, publishExclusiveUpdateMarkerSync, readUpdateMarker } from "../install/update-marker.js";
3
3
  import { launchInstalledApp } from "../launch/update-launch.js";
4
4
  import { UpdateProcessFenceCancelledError, waitForUpdateProcesses } from "../locks/update-process-fence.js";
5
- import { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor } from "../install/update-swap.js";
5
+ import { readInstalledUpdateTreeDigest, readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor } from "../install/update-swap.js";
6
6
  import { acquireUpdateLock, readUpdateStageState, writeUpdateStageState, writeUpdateStageStateDurably } from "../update-state-store.js";
7
7
  import { cancelUpdateLaunchGateBeforeTransition, publishUpdateLaunchGate, tryAcquireUpdateHelperLiveness, waitForUpdateLaunchGateWriter } from "../launch/update-launch-gate.js";
8
8
  import { isCanonicalPath } from "../../native/canonical-path.js";
@@ -337,7 +337,7 @@ async function runSchema3UpdateHelper(options, request, helperLiveness) {
337
337
  await syncUpdateTreeParent(candidate);
338
338
  await syncUpdateTreeParent(request.target);
339
339
  if (await readUpdateTreeVersion(request.target) !== swapping.version || await readUpdateTreeVersion(candidate) !== swapping.previousVersion || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(request.target), swapping.candidateTreeIdentity) || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(candidate), swapping.previousTreeIdentity)) throw new Error("Atomic update exchange produced unexpected tree versions");
340
- if (!sameUpdateTreeDigest(await readUpdateTreeDigest(request.target), swapping.candidateTreeDigest)) throw new Error("Installed update tree content changed during the directory exchange");
340
+ if (!sameUpdateTreeDigest(await readInstalledUpdateTreeDigest(request.target), swapping.candidateTreeDigest)) throw new Error("Installed update tree content changed during the directory exchange");
341
341
  completedDigestVerified = true;
342
342
  await writeUpdateStageStateDurably(options.staging, {
343
343
  ...swapping,
@@ -1,15 +1,47 @@
1
+ import { renameExclusive } from "../../native/native-rename.js";
1
2
  import { hasUpdateHelperArtifacts } from "./update-helper.js";
2
3
  import { updateProcessMayBeAlive } from "../locks/update-process-liveness.js";
3
4
  import { UpdateLockBusyError, acquireUpdateLock, readUpdateStageState } from "../update-state-store.js";
4
5
  import { readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, updateStagingFor } from "../install/update-swap.js";
5
6
  import { acquireRetainedUpdateTrees, acquireRetainedUpdateTreesWhileLocked } from "../retention/retirement-inventory.js";
6
7
  import { reconcileRetirementCleanupMarkerWhileLocked, retireCompletedUpdateWhileLocked } from "../retention/update-retirement.js";
8
+ import { matchesOldTree, updateRetirementPaths } from "../retention/retirement-records.js";
7
9
  import { readUpdateLaunchGate } from "../launch/update-launch-gate.js";
8
- import { exists, readTreeDigestForProof, reconcileSwap, recoverLegacyHandoff, recoverStagedCandidate, resetToStaged } from "./resume-staging.js";
10
+ import { exists, hasUnknownStagingEntries, readInstalledTreeDigestForProof, reconcileSwap, recoverLegacyHandoff, recoverStagedCandidate, resetToStaged } from "./resume-staging.js";
9
11
  import { recoverUpdateLaunchGate } from "./launch-gate-recovery.js";
10
12
  import { lstat, readFile, readdir, rmdir, unlink } from "node:fs/promises";
11
13
  import { join } from "node:path";
14
+ import { randomUUID } from "node:crypto";
12
15
  // src/updates/helper/update-resume.ts
16
+ /**
17
+ * A completed exchange that can no longer be retired must not strand the app.
18
+ * The exchange already finished, so the staging directory only holds the
19
+ * previous tree and the journal. When no retirement record was started for
20
+ * this generation and the previous tree is intact, move the whole directory
21
+ * aside (never delete it) so the next update can stage normally. Retiring and
22
+ * retired phases own retirement records and keep failing closed.
23
+ */
24
+ async function setAsideStaleCompletedStaging(options) {
25
+ const { target, staging, state } = options;
26
+ try {
27
+ const targetInfo = await lstat(target);
28
+ if (!targetInfo.isDirectory() || targetInfo.isSymbolicLink()) return { status: "recovery-required" };
29
+ const installedVersion = await readUpdateTreeVersion(target);
30
+ if (!installedVersion) return { status: "recovery-required" };
31
+ const paths = updateRetirementPaths(target, state.generation);
32
+ if (await exists(paths.claim) || await exists(paths.container)) return { status: "recovery-required" };
33
+ if (await hasUnknownStagingEntries(staging, [], state.generation) || !await matchesOldTree(join(staging, "candidate"), state)) return { status: "recovery-required" };
34
+ const current = await readUpdateStageState(staging);
35
+ if (!current || current.generation !== state.generation || current.phase !== "completed") return { status: "recovery-required" };
36
+ renameExclusive(staging, `${staging}.stale-${randomUUID()}`);
37
+ return installedVersion === state.version ? {
38
+ status: "updated",
39
+ version: state.version
40
+ } : { status: "not-applied" };
41
+ } catch {
42
+ return { status: "recovery-required" };
43
+ }
44
+ }
13
45
  async function resumeLocked(options) {
14
46
  const { target, staging, trust, currentVersion } = options;
15
47
  const launchGate = await readUpdateLaunchGate(target);
@@ -121,19 +153,22 @@ async function resumeLocked(options) {
121
153
  });
122
154
  }
123
155
  if (state.phase === "completed") {
124
- if (await readUpdateTreeVersion(target) !== state.version || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(target), state.candidateTreeIdentity) || state.candidateTreeDigest !== void 0 && !sameUpdateTreeDigest(await readTreeDigestForProof(target), state.candidateTreeDigest)) return { status: "recovery-required" };
125
- if (!await retireCompletedUpdateWhileLocked({
156
+ if (await readUpdateTreeVersion(target) === state.version && sameUpdateTreeIdentity(await readUpdateTreeIdentity(target), state.candidateTreeIdentity) && (state.candidateTreeDigest === void 0 || sameUpdateTreeDigest(await readInstalledTreeDigestForProof(target), state.candidateTreeDigest)) && await retireCompletedUpdateWhileLocked({
126
157
  target,
127
158
  staging,
128
159
  state
129
- })) return { status: "recovery-required" };
130
- return {
160
+ })) return {
131
161
  status: "updated",
132
162
  version: state.version
133
163
  };
164
+ return setAsideStaleCompletedStaging({
165
+ target,
166
+ staging,
167
+ state
168
+ });
134
169
  }
135
170
  if (state.phase === "retiring" || state.phase === "retired") {
136
- if (await readUpdateTreeVersion(target) !== state.version || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(target), state.candidateTreeIdentity) || state.candidateTreeDigest !== void 0 && !sameUpdateTreeDigest(await readTreeDigestForProof(target), state.candidateTreeDigest)) return { status: "recovery-required" };
171
+ if (await readUpdateTreeVersion(target) !== state.version || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(target), state.candidateTreeIdentity) || state.candidateTreeDigest !== void 0 && !sameUpdateTreeDigest(await readInstalledTreeDigestForProof(target), state.candidateTreeDigest)) return { status: "recovery-required" };
137
172
  if (!await retireCompletedUpdateWhileLocked({
138
173
  target,
139
174
  staging,
@@ -30,8 +30,18 @@ export declare function sameUpdateTreeIdentity(left: UpdateTreeIdentity | undefi
30
30
  * host provides it, and compare lstat/fstat metadata before and after reads.
31
31
  * This detects ordinary concurrent changes by cooperating updater processes;
32
32
  * it is not an atomic filesystem snapshot against a hostile same-user writer.
33
+ *
34
+ * Candidate proofs refuse regular files with more than one hard link, because
35
+ * an alias outside the private staging tree could change bytes after the proof.
36
+ * Set `allowHardLinkedFiles` only to re-prove a tree that is already installed:
37
+ * the link count is not part of the digest, and backup, dedup or packaging
38
+ * tools may add a link to an installed file without changing its bytes.
33
39
  */
34
- export declare function readUpdateTreeDigest(tree: string): Promise<UpdateTreeDigest>;
40
+ export declare function readUpdateTreeDigest(tree: string, options?: Readonly<{
41
+ allowHardLinkedFiles?: boolean;
42
+ }>): Promise<UpdateTreeDigest>;
43
+ /** Re-prove an installed app tree; tolerates hard-linked regular files. */
44
+ export declare function readInstalledUpdateTreeDigest(tree: string): Promise<UpdateTreeDigest>;
35
45
  export declare function sameUpdateTreeDigest(left: UpdateTreeDigest | undefined, right: UpdateTreeDigest | undefined): boolean;
36
46
  /** Sync candidate file contents and directory entries before a gated schema-3 exchange. */
37
47
  export declare function syncUpdateTree(tree: string): Promise<void>;
@@ -52,8 +52,15 @@ function sameTreeEntrySnapshot(left, right) {
52
52
  * host provides it, and compare lstat/fstat metadata before and after reads.
53
53
  * This detects ordinary concurrent changes by cooperating updater processes;
54
54
  * it is not an atomic filesystem snapshot against a hostile same-user writer.
55
+ *
56
+ * Candidate proofs refuse regular files with more than one hard link, because
57
+ * an alias outside the private staging tree could change bytes after the proof.
58
+ * Set `allowHardLinkedFiles` only to re-prove a tree that is already installed:
59
+ * the link count is not part of the digest, and backup, dedup or packaging
60
+ * tools may add a link to an installed file without changing its bytes.
55
61
  */
56
- async function readUpdateTreeDigest(tree) {
62
+ async function readUpdateTreeDigest(tree, options = {}) {
63
+ const allowHardLinkedFiles = options.allowHardLinkedFiles === true;
57
64
  const hash = createHash("sha256");
58
65
  hash.update("adea-framework-update-tree\0v1\0", "utf8");
59
66
  const root = await lstat(tree, { bigint: true });
@@ -97,7 +104,7 @@ async function readUpdateTreeDigest(tree) {
97
104
  if (!sameTreeEntrySnapshot(before, await lstat(path, { bigint: true }))) throw new Error("Update tree changed while reading a directory");
98
105
  return;
99
106
  }
100
- if (!before.isFile() || before.nlink !== 1n || before.size < 0n) throw new Error("Update tree contains an unsupported filesystem entry");
107
+ if (!before.isFile() || before.nlink < 1n || !allowHardLinkedFiles && before.nlink !== 1n || before.size < 0n) throw new Error("Update tree contains an unsupported filesystem entry");
101
108
  writeRecord("file", relative, before.mode, before.size);
102
109
  const noFollow = constants$1.O_NOFOLLOW ?? 0;
103
110
  const file = await open(path, constants$1.O_RDONLY | noFollow | (constants$1.O_NONBLOCK ?? 0));
@@ -126,6 +133,10 @@ async function readUpdateTreeDigest(tree) {
126
133
  hash.update(count);
127
134
  return hash.digest("hex");
128
135
  }
136
+ /** Re-prove an installed app tree; tolerates hard-linked regular files. */
137
+ function readInstalledUpdateTreeDigest(tree) {
138
+ return readUpdateTreeDigest(tree, { allowHardLinkedFiles: true });
139
+ }
129
140
  function sameUpdateTreeDigest(left, right) {
130
141
  return typeof left === "string" && typeof right === "string" && isSha256Hex(left) && left === right;
131
142
  }
@@ -219,4 +230,4 @@ async function swapUpdateTreeWhileLocked(options, exchangeOperation = exchangeDi
219
230
  ]);
220
231
  if (nextTargetVersion !== candidateVersion || nextCandidateVersion !== previousVersion || !sameUpdateTreeIdentity(nextTargetId, candidateIdentity) || !sameUpdateTreeIdentity(nextCandidateId, previousIdentity)) throw new Error("Atomic update exchange did not preserve both app trees");
221
232
  }
222
- export { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTree, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor, updateTreeIdentityFromStat };
233
+ export { readInstalledUpdateTreeDigest, readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTree, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor, updateTreeIdentityFromStat };