@adea-ai/app-framework 0.27.0 → 0.28.1

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.
Files changed (125) hide show
  1. package/README.md +177 -15
  2. package/dist/app/create-application.d.ts +2 -0
  3. package/dist/app/create-application.js +6 -0
  4. package/dist/app/service-registry.js +4 -0
  5. package/dist/appearance/custom-theme-import.js +43 -7
  6. package/dist/appearance/custom-theme-library.d.ts +2 -0
  7. package/dist/appearance/custom-theme-library.js +5 -1
  8. package/dist/appearance/theme-record-adapter.js +4 -2
  9. package/dist/appearance/theme-registry.js +7 -1
  10. package/dist/cli/cli-runner.d.ts +4 -0
  11. package/dist/cli/cli-runner.js +14 -1
  12. package/dist/cli/create-application-cli.js +4 -2
  13. package/dist/cli/release-cut-cli.js +2 -2
  14. package/dist/cli/update-helper-cli.js +28 -6
  15. package/dist/desktop/client-asset-manifest.d.ts +47 -0
  16. package/dist/desktop/client-asset-manifest.js +114 -0
  17. package/dist/desktop/client-asset-stream.d.ts +10 -0
  18. package/dist/desktop/client-asset-stream.js +138 -33
  19. package/dist/desktop/client-assets.d.ts +20 -0
  20. package/dist/desktop/client-assets.js +132 -22
  21. package/dist/desktop/client-response-lifecycle.d.ts +22 -0
  22. package/dist/desktop/client-response-lifecycle.js +233 -0
  23. package/dist/desktop/desktop-host.d.ts +40 -2
  24. package/dist/desktop/desktop-host.js +159 -9
  25. package/dist/framework-source.json +1 -1
  26. package/dist/installer/command-artifact.d.ts +4 -2
  27. package/dist/installer/command-artifact.js +119 -19
  28. package/dist/installer/linux-process-group.d.ts +13 -0
  29. package/dist/installer/linux-process-group.js +58 -0
  30. package/dist/native/darwin-sync.d.ts +7 -0
  31. package/dist/native/darwin-sync.js +43 -0
  32. package/dist/native/desktop-build-hook.js +7 -0
  33. package/dist/native/directory-exchange.d.ts +10 -0
  34. package/dist/native/directory-exchange.js +90 -0
  35. package/dist/native/electrobun-source-patch.d.ts +5 -0
  36. package/dist/native/electrobun-source-patch.js +19 -1
  37. package/dist/native/posix-launcher-build.d.ts +24 -0
  38. package/dist/native/posix-launcher-build.js +232 -0
  39. package/dist/native/posix-tree-removal.d.ts +36 -0
  40. package/dist/native/posix-tree-removal.js +425 -0
  41. package/dist/release/feed-release-cut.js +30 -10
  42. package/dist/release/github-release-cut.js +16 -0
  43. package/dist/release/release-cut.d.ts +8 -1
  44. package/dist/release/release-cut.js +9 -1
  45. package/dist/update-helper.bundle.js +1483 -105
  46. package/dist/updates/channel-update-manager.d.ts +5 -0
  47. package/dist/updates/channel-update-manager.js +13 -1
  48. package/dist/updates/desktop-updater.d.ts +78 -2
  49. package/dist/updates/desktop-updater.js +320 -37
  50. package/dist/updates/launch-environment.d.ts +2 -0
  51. package/dist/updates/launch-environment.js +4 -0
  52. package/dist/updates/native-file-lock.d.ts +15 -0
  53. package/dist/updates/native-file-lock.js +189 -0
  54. package/dist/updates/packaged-launch-admission.d.ts +13 -0
  55. package/dist/updates/packaged-launch-admission.js +45 -0
  56. package/dist/updates/packaged-release-config.d.ts +18 -0
  57. package/dist/updates/packaged-release-config.js +60 -0
  58. package/dist/updates/packaged-update-startup.d.ts +44 -0
  59. package/dist/updates/packaged-update-startup.js +81 -0
  60. package/dist/updates/update-arm.d.ts +9 -8
  61. package/dist/updates/update-arm.js +227 -62
  62. package/dist/updates/update-cleanup-error.d.ts +23 -0
  63. package/dist/updates/update-cleanup-error.js +65 -0
  64. package/dist/updates/update-download-cleanup.d.ts +11 -0
  65. package/dist/updates/update-download-cleanup.js +112 -2
  66. package/dist/updates/update-download-lock.d.ts +20 -0
  67. package/dist/updates/update-download-lock.js +73 -0
  68. package/dist/updates/update-download.d.ts +2 -0
  69. package/dist/updates/update-download.js +7 -3
  70. package/dist/updates/update-generation-lease.d.ts +6 -0
  71. package/dist/updates/update-generation-lease.js +14 -0
  72. package/dist/updates/update-helper.d.ts +11 -2
  73. package/dist/updates/update-helper.js +322 -13
  74. package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
  75. package/dist/updates/update-inherited-launch-lease.js +58 -0
  76. package/dist/updates/update-instance-lease.d.ts +15 -0
  77. package/dist/updates/update-instance-lease.js +25 -0
  78. package/dist/updates/update-launch-gate.d.ts +137 -0
  79. package/dist/updates/update-launch-gate.js +617 -0
  80. package/dist/updates/update-launch.js +3 -1
  81. package/dist/updates/update-lock.d.ts +12 -0
  82. package/dist/updates/update-lock.js +18 -0
  83. package/dist/updates/update-manager.d.ts +2 -0
  84. package/dist/updates/update-manager.js +9 -2
  85. package/dist/updates/update-marker.d.ts +7 -0
  86. package/dist/updates/update-marker.js +62 -0
  87. package/dist/updates/update-preflight-error.d.ts +7 -0
  88. package/dist/updates/update-preflight-error.js +11 -0
  89. package/dist/updates/update-process-fence.d.ts +4 -0
  90. package/dist/updates/update-process-fence.js +85 -73
  91. package/dist/updates/update-process-liveness.d.ts +2 -0
  92. package/dist/updates/update-process-liveness.js +11 -0
  93. package/dist/updates/update-resume.d.ts +37 -3
  94. package/dist/updates/update-resume.js +839 -23
  95. package/dist/updates/update-retention-marker.d.ts +67 -0
  96. package/dist/updates/update-retention-marker.js +165 -0
  97. package/dist/updates/update-retention-plan.d.ts +25 -0
  98. package/dist/updates/update-retention-plan.js +54 -0
  99. package/dist/updates/update-retention-sync.d.ts +34 -0
  100. package/dist/updates/update-retention-sync.js +83 -0
  101. package/dist/updates/update-retirement.d.ts +205 -0
  102. package/dist/updates/update-retirement.js +1485 -0
  103. package/dist/updates/update-shutdown.d.ts +16 -4
  104. package/dist/updates/update-shutdown.js +133 -8
  105. package/dist/updates/update-state-store.d.ts +58 -0
  106. package/dist/updates/update-state-store.js +139 -0
  107. package/dist/updates/update-swap-stage.d.ts +1 -1
  108. package/dist/updates/update-swap-stage.js +85 -14
  109. package/dist/updates/update-swap.d.ts +45 -2
  110. package/dist/updates/update-swap.js +207 -17
  111. package/package.json +31 -1
  112. package/src/appearance/custom-theme-import.ts +96 -14
  113. package/src/appearance/custom-theme-library.ts +5 -0
  114. package/src/appearance/theme-record-adapter.ts +15 -6
  115. package/src/appearance/theme-registry.ts +8 -1
  116. package/src/desktop/client-asset-manifest.ts +207 -0
  117. package/src/desktop/client-asset-stream.ts +193 -32
  118. package/src/desktop/client-assets.ts +210 -19
  119. package/src/desktop/client-response-lifecycle.ts +305 -0
  120. package/src/native/electrobun-posix-launch-lease.patch +398 -0
  121. package/templates/application/README.md +50 -0
  122. package/templates/application/electrobun.config.ts +5 -1
  123. package/templates/application/scripts/build-desktop.ts +4 -0
  124. package/templates/application/src/bun/index.ts +173 -16
  125. package/templates/application/vite.config.ts +112 -6
@@ -1,15 +1,27 @@
1
+ export type UpdateShutdownTiming = Readonly<{
2
+ /** Conservative monotonic deadline derived from the armed helper's process timeout. */
3
+ deadline: number;
4
+ /** Remaining time before the app must exit, excluding the cancellation margin. */
5
+ remainingMs(): number;
6
+ }>;
1
7
  /**
2
8
  * Reserve an app's existing quit approval before arming a post-exit helper.
3
9
  * The native adapter must guarantee its token cannot be reused or vetoed again.
4
- * `arm` must clean up partial startup before rejecting, and `quit` must only
5
- * resolve after shutdown is accepted. The helper still needs a bounded process
6
- * fence; this ordering alone does not establish that the app has exited.
10
+ * `arm` must either clean up partial startup or reject with a retryable cleanup
11
+ * handle. `quit` must only resolve after shutdown is accepted. The helper still
12
+ * needs a bounded process fence; this ordering alone does not establish that
13
+ * the app has exited. Optional quit preparation runs with the helper armed. If
14
+ * any later step fails, the helper must be canceled before preparation is
15
+ * aborted so the host resumes only after the launch gate is clear.
7
16
  */
8
17
  export declare function scheduleUpdateShutdown<Token>(options: {
9
18
  reserve(): Token | null | Promise<Token | null>;
10
19
  cancelReservation(token: Token): void | Promise<void>;
11
20
  arm(): Promise<{
12
21
  cancel(): void | Promise<void>;
22
+ processDeadline?: number;
13
23
  }>;
14
- quit(token: Token): boolean | Promise<boolean>;
24
+ prepareQuit?(token: Token, timing?: UpdateShutdownTiming): void | Promise<void>;
25
+ abortPreparedQuit?(token: Token): void | Promise<void>;
26
+ quit(token: Token, timing?: UpdateShutdownTiming): boolean | Promise<boolean>;
15
27
  }): Promise<'cancelled' | 'scheduled'>;
@@ -1,29 +1,154 @@
1
+ import { UpdateCleanupPendingError, UpdateCleanupTerminalError, findUpdateCleanupTerminalError } from "./update-cleanup-error.js";
1
2
  // src/updates/update-shutdown.ts
3
+ /** Helper process-fence time left reserved for cancellation and gate cleanup. */
4
+ var UPDATE_HELPER_CANCEL_MARGIN_MS = 11e3;
5
+ async function settleCleanupStep(operation, recordTerminal) {
6
+ try {
7
+ await operation();
8
+ } catch (retryError) {
9
+ const terminal = findUpdateCleanupTerminalError(retryError);
10
+ if (!terminal) throw retryError;
11
+ recordTerminal(terminal);
12
+ }
13
+ }
2
14
  /**
3
15
  * Reserve an app's existing quit approval before arming a post-exit helper.
4
16
  * The native adapter must guarantee its token cannot be reused or vetoed again.
5
- * `arm` must clean up partial startup before rejecting, and `quit` must only
6
- * resolve after shutdown is accepted. The helper still needs a bounded process
7
- * fence; this ordering alone does not establish that the app has exited.
17
+ * `arm` must either clean up partial startup or reject with a retryable cleanup
18
+ * handle. `quit` must only resolve after shutdown is accepted. The helper still
19
+ * needs a bounded process fence; this ordering alone does not establish that
20
+ * the app has exited. Optional quit preparation runs with the helper armed. If
21
+ * any later step fails, the helper must be canceled before preparation is
22
+ * aborted so the host resumes only after the launch gate is clear.
8
23
  */
9
24
  async function scheduleUpdateShutdown(options) {
25
+ if (Boolean(options.prepareQuit) !== Boolean(options.abortPreparedQuit)) throw new Error("Update quit preparation requires a recovery callback");
10
26
  const token = await options.reserve();
11
27
  if (token === null) return "cancelled";
12
28
  if (token === void 0) throw new Error("Invalid update quit approval");
13
29
  let helper;
30
+ let preparationAttempted = false;
31
+ let timing;
14
32
  try {
15
33
  helper = await options.arm();
16
34
  if (!helper || typeof helper.cancel !== "function") throw new Error("Update helper was not armed");
17
- if (await options.quit(token) !== true) throw new Error("Update shutdown rejected");
35
+ if (helper.processDeadline !== void 0) {
36
+ if (!Number.isFinite(helper.processDeadline) || helper.processDeadline < 0) throw new Error("Update helper returned an invalid process deadline");
37
+ const processDeadline = helper.processDeadline;
38
+ timing = {
39
+ deadline: processDeadline - UPDATE_HELPER_CANCEL_MARGIN_MS,
40
+ remainingMs: () => Math.max(0, processDeadline - UPDATE_HELPER_CANCEL_MARGIN_MS - performance.now())
41
+ };
42
+ if (timing.remainingMs() < 1) throw new Error("Insufficient helper process time remains for a safe shutdown");
43
+ }
44
+ if (options.prepareQuit) {
45
+ preparationAttempted = true;
46
+ await options.prepareQuit(token, timing);
47
+ }
48
+ if (await options.quit(token, timing) !== true) throw new Error("Update shutdown rejected");
18
49
  return "scheduled";
19
- } catch {
50
+ } catch (error) {
51
+ let cleanupError;
20
52
  try {
21
53
  await helper?.cancel();
22
- } catch {}
54
+ } catch (failed) {
55
+ cleanupError = failed;
56
+ }
57
+ const helperTerminalError = findUpdateCleanupTerminalError(cleanupError);
58
+ let terminalCleanupError = helperTerminalError ?? findUpdateCleanupTerminalError(error);
59
+ const helperCleanupRetryable = cleanupError instanceof UpdateCleanupPendingError || cleanupError !== void 0 && helperTerminalError === void 0;
60
+ const originalPendingRetryable = error instanceof UpdateCleanupPendingError && error !== cleanupError;
61
+ let preparationAbortSettled = !preparationAttempted || options.abortPreparedQuit === void 0;
62
+ let preparationError;
63
+ if (!preparationAbortSettled && cleanupError === void 0 && !(error instanceof UpdateCleanupPendingError) && terminalCleanupError === void 0) try {
64
+ await options.abortPreparedQuit(token);
65
+ preparationAbortSettled = true;
66
+ } catch (failed) {
67
+ preparationError = failed;
68
+ terminalCleanupError = findUpdateCleanupTerminalError(failed);
69
+ }
70
+ const preparationAbortRetryable = preparationError !== void 0 && findUpdateCleanupTerminalError(preparationError) === void 0;
71
+ if (helperCleanupRetryable || originalPendingRetryable || preparationAbortRetryable) {
72
+ let helperCleanupSettled = cleanupError === void 0 || helperTerminalError !== void 0;
73
+ let originalPendingSettled = !(error instanceof UpdateCleanupPendingError) || error === cleanupError;
74
+ let reservationReleased = false;
75
+ let terminalFailure = terminalCleanupError;
76
+ let pendingError;
77
+ const retryCleanup = async () => {
78
+ if (!helperCleanupSettled) {
79
+ pendingError.markStage("helper-cleanup");
80
+ await settleCleanupStep(() => cleanupError instanceof UpdateCleanupPendingError ? cleanupError.retryCleanup() : helper?.cancel(), (terminal) => {
81
+ const committed = terminalFailure ?? terminal;
82
+ terminalFailure = committed;
83
+ pendingError.markTerminal(committed);
84
+ });
85
+ helperCleanupSettled = true;
86
+ }
87
+ if (!originalPendingSettled) {
88
+ if (error instanceof UpdateCleanupPendingError) pendingError.markStage(error.stage);
89
+ await settleCleanupStep(() => error.retryCleanup(), (terminal) => {
90
+ const committed = terminalFailure ?? terminal;
91
+ terminalFailure = committed;
92
+ pendingError.markTerminal(committed);
93
+ });
94
+ originalPendingSettled = true;
95
+ }
96
+ if (!preparationAbortSettled && terminalFailure === void 0) {
97
+ pendingError.markStage("quit-preparation-resume");
98
+ await settleCleanupStep(() => options.abortPreparedQuit(token), (terminal) => {
99
+ const committed = terminalFailure ?? terminal;
100
+ terminalFailure = committed;
101
+ pendingError.markTerminal(committed);
102
+ });
103
+ preparationAbortSettled = true;
104
+ }
105
+ if (!reservationReleased) {
106
+ pendingError.markStage("quit-approval-release");
107
+ await options.cancelReservation(token);
108
+ reservationReleased = true;
109
+ }
110
+ };
111
+ const initialStage = !helperCleanupSettled ? "helper-cleanup" : !originalPendingSettled && error instanceof UpdateCleanupPendingError ? error.stage : !preparationAbortSettled ? "quit-preparation-resume" : "quit-approval-release";
112
+ pendingError = new UpdateCleanupPendingError("Update shutdown could not be scheduled; helper cleanup remains pending", [
113
+ error,
114
+ ...cleanupError === void 0 ? [] : [cleanupError],
115
+ ...preparationError === void 0 ? [] : [preparationError]
116
+ ], retryCleanup, initialStage);
117
+ if (terminalFailure) pendingError.markTerminal(terminalFailure);
118
+ throw pendingError;
119
+ }
120
+ if (terminalCleanupError) {
121
+ try {
122
+ await options.cancelReservation(token);
123
+ } catch (reservationError) {
124
+ const pending = new UpdateCleanupPendingError("Update shutdown failed after a terminal helper transition; quit approval release is pending", [
125
+ error,
126
+ ...cleanupError === void 0 ? [] : [cleanupError],
127
+ ...preparationError === void 0 ? [] : [preparationError],
128
+ terminalCleanupError,
129
+ reservationError
130
+ ], async () => options.cancelReservation(token));
131
+ pending.markTerminal(terminalCleanupError);
132
+ pending.markStage("quit-approval-release");
133
+ throw pending;
134
+ }
135
+ throw new UpdateCleanupTerminalError("Update shutdown could not be scheduled because the helper transition is committed or requires recovery", [
136
+ error,
137
+ ...cleanupError === void 0 ? [] : [cleanupError],
138
+ ...preparationError === void 0 ? [] : [preparationError],
139
+ terminalCleanupError
140
+ ]);
141
+ }
23
142
  try {
24
143
  await options.cancelReservation(token);
25
- } catch {}
26
- throw new Error("Update shutdown could not be scheduled");
144
+ } catch (reservationError) {
145
+ throw new UpdateCleanupPendingError("Update shutdown could not be scheduled; quit approval release is pending", [
146
+ error,
147
+ ...preparationError === void 0 ? [] : [preparationError],
148
+ reservationError
149
+ ], async () => options.cancelReservation(token), "quit-approval-release");
150
+ }
151
+ throw new Error("Update shutdown could not be scheduled", { cause: error });
27
152
  }
28
153
  }
29
154
  export { scheduleUpdateShutdown };
@@ -0,0 +1,58 @@
1
+ import { type UpdateLock } from './update-lock';
2
+ import type { SignedRelease } from './signed-release';
3
+ type UpdateStagePhase = 'staged' | 'armed' | 'swapping' | 'completed' | 'retiring' | 'retired' | 'failed';
4
+ export type UpdateStageState = Readonly<{
5
+ schema: 1;
6
+ generation: string;
7
+ phase: UpdateStagePhase;
8
+ version: string;
9
+ previousVersion: string;
10
+ /** Device/inode of the extracted candidate, persisted before helper handoff. */
11
+ candidateTreeIdentity?: Readonly<{
12
+ device: string;
13
+ inode: string;
14
+ }>;
15
+ /** SHA-256 integrity checkpoint for the complete extracted candidate tree. */
16
+ candidateTreeDigest?: string;
17
+ /** Filesystem identity of the previous install, captured before atomic exchange. */
18
+ previousTreeIdentity?: Readonly<{
19
+ device: string;
20
+ inode: string;
21
+ }>;
22
+ /** The authenticated release identity needed to recover and retry this candidate. */
23
+ signedRelease?: SignedRelease;
24
+ helperPid?: number;
25
+ /** Exact owner bound into a schema-3 helper request and its argv. */
26
+ helperOwner?: string;
27
+ /** OS-liveness owner of the schema-3 launch gate published by this helper. */
28
+ launchGateOwner?: string;
29
+ }>;
30
+ export declare class UpdateLockBusyError extends Error {
31
+ constructor();
32
+ }
33
+ /** Acquire the stable per-install lock, waiting briefly for short transitions. */
34
+ export declare function acquireUpdateLock(target: string, timeoutMs?: number): Promise<UpdateLock>;
35
+ export declare function newUpdateStageState(input: {
36
+ version: string;
37
+ previousVersion: string;
38
+ candidateTreeIdentity: Readonly<{
39
+ device: string;
40
+ inode: string;
41
+ }>;
42
+ candidateTreeDigest: string;
43
+ signedRelease: SignedRelease;
44
+ }): UpdateStageState;
45
+ export declare function readUpdateStageState(staging: string): Promise<UpdateStageState | undefined>;
46
+ /** Sync a journal directory after a state rename or owned-entry cleanup. */
47
+ export declare function syncUpdateStageDirectory(staging: string): Promise<void>;
48
+ export declare function writeUpdateStageState(staging: string, state: UpdateStageState): Promise<void>;
49
+ /**
50
+ * Atomically replace and sync a journal record before a schema-3 gate decision.
51
+ * A successful return means both the temporary file contents and the rename's
52
+ * containing directory were synced. If the filesystem cannot provide that
53
+ * proof, callers must keep the launch gate and require recovery.
54
+ */
55
+ export declare function writeUpdateStageStateDurably(staging: string, state: UpdateStageState): Promise<void>;
56
+ /** Run one operation while holding the per-install staging lock. */
57
+ export declare function withUpdateLock<T>(target: string, operation: () => Promise<T>): Promise<T>;
58
+ export {};
@@ -0,0 +1,139 @@
1
+ import { tryAcquireUpdateLock } from "./update-lock.js";
2
+ import { lstat, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { constants as constants$1 } from "node:fs";
5
+ import { randomUUID } from "node:crypto";
6
+ // src/updates/update-state-store.ts
7
+ var UpdateLockBusyError = class extends Error {
8
+ constructor() {
9
+ super("Another app instance is changing the staged update");
10
+ this.name = "UpdateLockBusyError";
11
+ }
12
+ };
13
+ /** Acquire the stable per-install lock, waiting briefly for short transitions. */
14
+ async function acquireUpdateLock(target, timeoutMs = 5e3) {
15
+ const deadline = Date.now() + timeoutMs;
16
+ while (true) {
17
+ const lock = await tryAcquireUpdateLock(target);
18
+ if (lock) return lock;
19
+ if (Date.now() >= deadline) throw new UpdateLockBusyError();
20
+ await Bun.sleep(Math.min(25, Math.max(1, deadline - Date.now())));
21
+ }
22
+ }
23
+ function newUpdateStageState(input) {
24
+ return Object.freeze({
25
+ schema: 1,
26
+ generation: randomUUID(),
27
+ phase: "staged",
28
+ version: input.version,
29
+ previousVersion: input.previousVersion,
30
+ candidateTreeIdentity: input.candidateTreeIdentity,
31
+ candidateTreeDigest: input.candidateTreeDigest,
32
+ signedRelease: input.signedRelease
33
+ });
34
+ }
35
+ function parseState(value) {
36
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid update staging state");
37
+ const record = value;
38
+ const candidateTreeIdentity = record.candidateTreeIdentity;
39
+ const candidateTreeDigest = record.candidateTreeDigest;
40
+ const previousTreeIdentity = record.previousTreeIdentity;
41
+ if (record.schema !== 1 || typeof record.generation !== "string" || !/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(record.generation) || ![
42
+ "staged",
43
+ "armed",
44
+ "swapping",
45
+ "completed",
46
+ "retiring",
47
+ "retired",
48
+ "failed"
49
+ ].includes(String(record.phase)) || typeof record.version !== "string" || !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(record.version) || typeof record.previousVersion !== "string" || !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(record.previousVersion) || candidateTreeDigest !== void 0 && (typeof candidateTreeDigest !== "string" || !/^[0-9a-f]{64}$/.test(candidateTreeDigest)) || candidateTreeIdentity !== void 0 && (typeof candidateTreeIdentity !== "object" || candidateTreeIdentity === null || Array.isArray(candidateTreeIdentity) || Object.keys(candidateTreeIdentity).length !== 2 || typeof candidateTreeIdentity.device !== "string" || !/^[1-9]\d{0,19}$/.test(candidateTreeIdentity.device) || typeof candidateTreeIdentity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(candidateTreeIdentity.inode)) || previousTreeIdentity !== void 0 && (typeof previousTreeIdentity !== "object" || previousTreeIdentity === null || Array.isArray(previousTreeIdentity) || Object.keys(previousTreeIdentity).length !== 2 || typeof previousTreeIdentity.device !== "string" || !/^[1-9]\d{0,19}$/.test(previousTreeIdentity.device) || typeof previousTreeIdentity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(previousTreeIdentity.inode)) || record.signedRelease !== void 0 && (typeof record.signedRelease !== "object" || record.signedRelease === null || Array.isArray(record.signedRelease) || Object.keys(record.signedRelease).length !== 2 || !Object.hasOwn(record.signedRelease, "descriptor") || typeof record.signedRelease.signature !== "string") || record.helperPid !== void 0 && (!Number.isSafeInteger(record.helperPid) || record.helperPid < 2) || record.helperOwner !== void 0 && (typeof record.helperOwner !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.helperOwner)) || record.launchGateOwner !== void 0 && (typeof record.launchGateOwner !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.launchGateOwner)) || Object.keys(record).some((key) => ![
50
+ "schema",
51
+ "generation",
52
+ "phase",
53
+ "version",
54
+ "previousVersion",
55
+ "candidateTreeIdentity",
56
+ "candidateTreeDigest",
57
+ "previousTreeIdentity",
58
+ "signedRelease",
59
+ "helperPid",
60
+ "helperOwner",
61
+ "launchGateOwner"
62
+ ].includes(key))) throw new Error("Invalid update staging state");
63
+ if ((record.phase === "armed" || record.phase === "swapping" || record.phase === "completed" || record.phase === "retiring" || record.phase === "retired") && candidateTreeIdentity === void 0) throw new Error("Invalid update staging state");
64
+ if ((record.phase === "retiring" || record.phase === "retired") && previousTreeIdentity === void 0) throw new Error("Invalid update staging state");
65
+ return Object.freeze(record);
66
+ }
67
+ async function readUpdateStageState(staging) {
68
+ const path = join(staging, "state.json");
69
+ let info;
70
+ try {
71
+ info = await lstat(path);
72
+ } catch (error) {
73
+ if (error.code === "ENOENT") return void 0;
74
+ throw error;
75
+ }
76
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096) throw new Error("Invalid update staging state");
77
+ return parseState(JSON.parse(await readFile(path, "utf8")));
78
+ }
79
+ /** Sync a journal directory after a state rename or owned-entry cleanup. */
80
+ async function syncUpdateStageDirectory(staging) {
81
+ const directory = await open(staging, constants$1.O_RDONLY);
82
+ try {
83
+ await directory.sync();
84
+ } finally {
85
+ await directory.close();
86
+ }
87
+ }
88
+ async function writeUpdateStageState(staging, state) {
89
+ if (typeof state.generation !== "string" || !/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(state.generation)) throw new Error("Invalid update staging state");
90
+ const path = join(staging, "state.json");
91
+ const temporary = join(staging, `.state-${state.generation}-${randomUUID()}.tmp`);
92
+ await writeFile(temporary, JSON.stringify(state) + "\n", {
93
+ flag: "wx",
94
+ mode: 384
95
+ });
96
+ try {
97
+ await rename(temporary, path);
98
+ } catch (error) {
99
+ await unlink(temporary).catch(() => {});
100
+ throw error;
101
+ }
102
+ }
103
+ /**
104
+ * Atomically replace and sync a journal record before a schema-3 gate decision.
105
+ * A successful return means both the temporary file contents and the rename's
106
+ * containing directory were synced. If the filesystem cannot provide that
107
+ * proof, callers must keep the launch gate and require recovery.
108
+ */
109
+ async function writeUpdateStageStateDurably(staging, state) {
110
+ if (typeof state.generation !== "string" || !/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(state.generation)) throw new Error("Invalid update staging state");
111
+ const path = join(staging, "state.json");
112
+ const temporary = join(staging, `.state-${state.generation}-${randomUUID()}.tmp`);
113
+ let renamed = false;
114
+ try {
115
+ const file = await open(temporary, constants$1.O_WRONLY | constants$1.O_CREAT | constants$1.O_EXCL, 384);
116
+ try {
117
+ await file.writeFile(JSON.stringify(state) + "\n");
118
+ await file.sync();
119
+ } finally {
120
+ await file.close();
121
+ }
122
+ await rename(temporary, path);
123
+ renamed = true;
124
+ await syncUpdateStageDirectory(staging);
125
+ } catch (error) {
126
+ if (!renamed) await unlink(temporary).catch(() => {});
127
+ throw error;
128
+ }
129
+ }
130
+ /** Run one operation while holding the per-install staging lock. */
131
+ async function withUpdateLock(target, operation) {
132
+ const lock = await acquireUpdateLock(target);
133
+ try {
134
+ return await operation();
135
+ } finally {
136
+ await lock.release();
137
+ }
138
+ }
139
+ export { UpdateLockBusyError, acquireUpdateLock, newUpdateStageState, readUpdateStageState, syncUpdateStageDirectory, withUpdateLock, writeUpdateStageState, writeUpdateStageStateDurably };
@@ -1,5 +1,5 @@
1
1
  import type { InstallerPlatform, InstallerRenderer } from '../installer/installer-layout';
2
- import type { ReleaseTrust, VerifiedRelease } from './signed-release';
2
+ import { type ReleaseTrust, type VerifiedRelease } from './signed-release';
3
3
  /**
4
4
  * Extract an approved, signature-verified update into `candidate` inside a new
5
5
  * private staging directory beside the install. Does not stop, replace or
@@ -1,10 +1,21 @@
1
+ import { exportVerifiedRelease } from "./signed-release.js";
1
2
  import { planUpdateHandoff } from "./update-handoff-plan.js";
2
3
  import { extractVerifiedUpdate } from "./update-extraction.js";
3
4
  import { renameUpdateExclusive } from "./update-exclusive-rename.js";
4
- import { updateStagingFor } from "./update-swap.js";
5
+ import { newUpdateStageState, readUpdateStageState, withUpdateLock, writeUpdateStageState } from "./update-state-store.js";
6
+ import { readUpdateTreeDigest, readUpdateTreeIdentity, updateStagingFor } from "./update-swap.js";
7
+ import { assertNoUpdateRetentionPruneArtifactsWhileLocked, reconcileRetirementCleanupMarkerWhileLocked } from "./update-retirement.js";
5
8
  import { lstat, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
6
9
  import { join } from "node:path";
7
10
  // src/updates/update-swap-stage.ts
11
+ async function assertInstalledVersion(options) {
12
+ const info = await lstat(options.target);
13
+ if (!info.isDirectory() || info.isSymbolicLink() || await realpath(options.target) !== options.target) throw new Error("Invalid update install target");
14
+ const versionFile = join(options.target, ...options.platform === "macos-arm64" ? ["Contents", "Resources"] : ["Resources"], "version.json");
15
+ const versionInfo = await lstat(versionFile);
16
+ if (!versionInfo.isFile() || versionInfo.size > 1048576) throw new Error("Installed update version mismatch");
17
+ if (JSON.parse(await readFile(versionFile, "utf8")).version !== options.version) throw new Error("Installed update version mismatch");
18
+ }
8
19
  /**
9
20
  * Extract an approved, signature-verified update into `candidate` inside a new
10
21
  * private staging directory beside the install. Does not stop, replace or
@@ -18,12 +29,11 @@ async function stageUpdateSwap(options) {
18
29
  "linux-x64": "linux/x64"
19
30
  }[plan.platform];
20
31
  if (`${process.platform}/${process.arch}` !== expectedHost) throw new Error("Update requires the matching native platform");
21
- const info = await lstat(plan.target);
22
- if (!info.isDirectory() || info.isSymbolicLink() || await realpath(plan.target) !== plan.target) throw new Error("Invalid update install target");
23
- const versionFile = join(plan.target, ...plan.platform === "macos-arm64" ? ["Contents", "Resources"] : ["Resources"], "version.json");
24
- const versionInfo = await lstat(versionFile);
25
- if (!versionInfo.isFile() || versionInfo.size > 1048576) throw new Error("Installed update version mismatch");
26
- if (JSON.parse(await readFile(versionFile, "utf8")).version !== plan.currentVersion) throw new Error("Installed update version mismatch");
32
+ await assertInstalledVersion({
33
+ target: plan.target,
34
+ platform: plan.platform,
35
+ version: plan.currentVersion
36
+ });
27
37
  const staging = updateStagingFor(plan.target);
28
38
  const preparing = await mkdtemp(`${staging}.preparing-`);
29
39
  const candidate = join(staging, "candidate");
@@ -41,13 +51,74 @@ async function stageUpdateSwap(options) {
41
51
  ...options.sidecars === void 0 ? {} : { sidecars: options.sidecars }
42
52
  });
43
53
  renameUpdateExclusive(extracted.payload, join(preparing, "candidate"));
44
- renameUpdateExclusive(preparing, staging);
45
- published = true;
46
- return {
47
- staging,
48
- candidate,
49
- version: plan.version
50
- };
54
+ await rm(extracted.directory, {
55
+ recursive: true,
56
+ force: true
57
+ });
58
+ const candidateTreeIdentity = await readUpdateTreeIdentity(join(preparing, "candidate"));
59
+ if (!candidateTreeIdentity) throw new Error("Update candidate tree identity could not be read");
60
+ const candidateTreeDigest = await readUpdateTreeDigest(join(preparing, "candidate"));
61
+ await writeUpdateStageState(preparing, newUpdateStageState({
62
+ version: plan.version,
63
+ previousVersion: options.currentVersion,
64
+ candidateTreeIdentity,
65
+ candidateTreeDigest,
66
+ signedRelease: exportVerifiedRelease(options.descriptor, options.trust)
67
+ }));
68
+ if (!await readUpdateStageState(preparing)) throw new Error("Update staging state was not written");
69
+ const result = await withUpdateLock(plan.target, async () => {
70
+ await assertNoUpdateRetentionPruneArtifactsWhileLocked(plan.target);
71
+ await assertInstalledVersion({
72
+ target: plan.target,
73
+ platform: plan.platform,
74
+ version: plan.currentVersion
75
+ });
76
+ let existingInfo;
77
+ try {
78
+ existingInfo = await lstat(staging);
79
+ } catch (error) {
80
+ if (error.code === "ENOENT") {
81
+ if (await reconcileRetirementCleanupMarkerWhileLocked({
82
+ target: plan.target,
83
+ staging,
84
+ currentVersion: plan.currentVersion
85
+ }) === "recovery-required") throw new Error("A previous update retirement requires recovery", { cause: error });
86
+ renameUpdateExclusive(preparing, staging);
87
+ published = true;
88
+ return {
89
+ staging,
90
+ candidate,
91
+ version: plan.version
92
+ };
93
+ }
94
+ throw error;
95
+ }
96
+ if (!existingInfo.isDirectory() || existingInfo.isSymbolicLink()) throw new Error("Unexpected update staging entry");
97
+ if (!await readUpdateStageState(staging)) {
98
+ const retirement = await reconcileRetirementCleanupMarkerWhileLocked({
99
+ target: plan.target,
100
+ staging,
101
+ currentVersion: plan.currentVersion
102
+ });
103
+ if (retirement === "updated") {
104
+ renameUpdateExclusive(preparing, staging);
105
+ published = true;
106
+ return {
107
+ staging,
108
+ candidate,
109
+ version: plan.version
110
+ };
111
+ }
112
+ if (retirement === "recovery-required") throw new Error("A previous update retirement requires recovery");
113
+ throw new Error("An older update is staged and needs recovery");
114
+ }
115
+ throw new Error("Another update is already staged or in progress");
116
+ });
117
+ if (!published) await rm(preparing, {
118
+ recursive: true,
119
+ force: true
120
+ });
121
+ return result;
51
122
  } finally {
52
123
  if (!published) await rm(preparing, {
53
124
  recursive: true,
@@ -1,10 +1,53 @@
1
+ import { exchangeDirectories } from '../native/directory-exchange';
2
+ export type UpdateTreeIdentity = Readonly<{
3
+ device: string;
4
+ inode: string;
5
+ }>;
6
+ export type UpdateTreeDigest = string;
7
+ type UpdateTreeStatIdentity = Readonly<{
8
+ dev: bigint;
9
+ ino: bigint;
10
+ isDirectory(): boolean;
11
+ isSymbolicLink(): boolean;
12
+ }>;
1
13
  /** The private staging directory the framework keeps beside an install. */
2
14
  export declare function updateStagingFor(target: string): string;
15
+ /** Read a version marker from an app tree, returning undefined when it is absent or invalid. */
16
+ export declare function readUpdateTreeVersion(tree: string): Promise<string | undefined>;
17
+ /** Capture only the stable device/inode pair; timestamps may be ctime fallbacks. */
18
+ export declare function updateTreeIdentityFromStat(info: UpdateTreeStatIdentity): UpdateTreeIdentity | undefined;
19
+ /** Read a directory's device/inode identity without Number precision loss. */
20
+ export declare function readUpdateTreeIdentity(tree: string): Promise<UpdateTreeIdentity | undefined>;
21
+ export declare function sameUpdateTreeIdentity(left: UpdateTreeIdentity | undefined, right: UpdateTreeIdentity | undefined): boolean;
3
22
  /**
4
- * Move the staged `candidate` into the install location once the app has
5
- * exited. The old tree is moved aside into staging and deleted.
23
+ * Compute a deterministic integrity digest for a complete extracted app tree.
24
+ * The manifest binds relative names, entry types, permission/special mode bits,
25
+ * regular-file sizes and bytes, and symbolic-link targets. It deliberately
26
+ * excludes ownership and timestamps. This digest is not signed authenticity;
27
+ * the signed release descriptor and verified archive establish provenance.
28
+ *
29
+ * Reads are no-follow by entry type, use O_NOFOLLOW for regular files when the
30
+ * host provides it, and compare lstat/fstat metadata before and after reads.
31
+ * This detects ordinary concurrent changes by cooperating updater processes;
32
+ * it is not an atomic filesystem snapshot against a hostile same-user writer.
33
+ */
34
+ export declare function readUpdateTreeDigest(tree: string): Promise<UpdateTreeDigest>;
35
+ export declare function sameUpdateTreeDigest(left: UpdateTreeDigest | undefined, right: UpdateTreeDigest | undefined): boolean;
36
+ /** Sync candidate file contents and directory entries before a gated schema-3 exchange. */
37
+ export declare function syncUpdateTree(tree: string): Promise<void>;
38
+ /** Sync parent directory entries after the atomic exchange has completed. */
39
+ export declare function syncUpdateTreeParent(target: string): Promise<void>;
40
+ /**
41
+ * Exchange the staged `candidate` and the install location atomically. The
42
+ * previous install remains at `staging/candidate` for journaled cleanup.
6
43
  */
7
44
  export declare function swapUpdateTree(options: {
8
45
  target: string;
9
46
  staging: string;
10
47
  }): Promise<void>;
48
+ /** Swap while the caller holds the per-install update lock. */
49
+ export declare function swapUpdateTreeWhileLocked(options: {
50
+ target: string;
51
+ staging: string;
52
+ }, exchangeOperation?: typeof exchangeDirectories): Promise<void>;
53
+ export {};