@adea-ai/app-framework 0.27.0 → 0.28.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.
Files changed (118) 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/create-application-cli.js +4 -2
  11. package/dist/cli/update-helper-cli.js +28 -6
  12. package/dist/desktop/client-asset-manifest.d.ts +47 -0
  13. package/dist/desktop/client-asset-manifest.js +114 -0
  14. package/dist/desktop/client-asset-stream.d.ts +10 -0
  15. package/dist/desktop/client-asset-stream.js +138 -33
  16. package/dist/desktop/client-assets.d.ts +20 -0
  17. package/dist/desktop/client-assets.js +132 -22
  18. package/dist/desktop/client-response-lifecycle.d.ts +22 -0
  19. package/dist/desktop/client-response-lifecycle.js +233 -0
  20. package/dist/desktop/desktop-host.d.ts +40 -2
  21. package/dist/desktop/desktop-host.js +159 -9
  22. package/dist/framework-source.json +1 -1
  23. package/dist/installer/command-artifact.d.ts +4 -2
  24. package/dist/installer/command-artifact.js +119 -19
  25. package/dist/installer/linux-process-group.d.ts +13 -0
  26. package/dist/installer/linux-process-group.js +58 -0
  27. package/dist/native/darwin-sync.d.ts +7 -0
  28. package/dist/native/darwin-sync.js +43 -0
  29. package/dist/native/desktop-build-hook.js +7 -0
  30. package/dist/native/directory-exchange.d.ts +10 -0
  31. package/dist/native/directory-exchange.js +90 -0
  32. package/dist/native/electrobun-source-patch.d.ts +5 -0
  33. package/dist/native/electrobun-source-patch.js +19 -1
  34. package/dist/native/posix-launcher-build.d.ts +24 -0
  35. package/dist/native/posix-launcher-build.js +232 -0
  36. package/dist/native/posix-tree-removal.d.ts +36 -0
  37. package/dist/native/posix-tree-removal.js +425 -0
  38. package/dist/update-helper.bundle.js +1483 -105
  39. package/dist/updates/channel-update-manager.d.ts +5 -0
  40. package/dist/updates/channel-update-manager.js +13 -1
  41. package/dist/updates/desktop-updater.d.ts +78 -2
  42. package/dist/updates/desktop-updater.js +320 -37
  43. package/dist/updates/launch-environment.d.ts +2 -0
  44. package/dist/updates/launch-environment.js +4 -0
  45. package/dist/updates/native-file-lock.d.ts +15 -0
  46. package/dist/updates/native-file-lock.js +189 -0
  47. package/dist/updates/packaged-launch-admission.d.ts +13 -0
  48. package/dist/updates/packaged-launch-admission.js +45 -0
  49. package/dist/updates/packaged-release-config.d.ts +18 -0
  50. package/dist/updates/packaged-release-config.js +60 -0
  51. package/dist/updates/packaged-update-startup.d.ts +44 -0
  52. package/dist/updates/packaged-update-startup.js +81 -0
  53. package/dist/updates/update-arm.d.ts +9 -8
  54. package/dist/updates/update-arm.js +227 -62
  55. package/dist/updates/update-cleanup-error.d.ts +23 -0
  56. package/dist/updates/update-cleanup-error.js +65 -0
  57. package/dist/updates/update-download-cleanup.d.ts +11 -0
  58. package/dist/updates/update-download-cleanup.js +112 -2
  59. package/dist/updates/update-download-lock.d.ts +20 -0
  60. package/dist/updates/update-download-lock.js +73 -0
  61. package/dist/updates/update-download.d.ts +2 -0
  62. package/dist/updates/update-download.js +7 -3
  63. package/dist/updates/update-generation-lease.d.ts +6 -0
  64. package/dist/updates/update-generation-lease.js +14 -0
  65. package/dist/updates/update-helper.d.ts +11 -2
  66. package/dist/updates/update-helper.js +322 -13
  67. package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
  68. package/dist/updates/update-inherited-launch-lease.js +58 -0
  69. package/dist/updates/update-instance-lease.d.ts +15 -0
  70. package/dist/updates/update-instance-lease.js +25 -0
  71. package/dist/updates/update-launch-gate.d.ts +137 -0
  72. package/dist/updates/update-launch-gate.js +617 -0
  73. package/dist/updates/update-launch.js +3 -1
  74. package/dist/updates/update-lock.d.ts +12 -0
  75. package/dist/updates/update-lock.js +18 -0
  76. package/dist/updates/update-manager.d.ts +2 -0
  77. package/dist/updates/update-manager.js +9 -2
  78. package/dist/updates/update-marker.d.ts +7 -0
  79. package/dist/updates/update-marker.js +62 -0
  80. package/dist/updates/update-preflight-error.d.ts +7 -0
  81. package/dist/updates/update-preflight-error.js +11 -0
  82. package/dist/updates/update-process-fence.d.ts +4 -0
  83. package/dist/updates/update-process-fence.js +85 -73
  84. package/dist/updates/update-process-liveness.d.ts +2 -0
  85. package/dist/updates/update-process-liveness.js +11 -0
  86. package/dist/updates/update-resume.d.ts +37 -3
  87. package/dist/updates/update-resume.js +839 -23
  88. package/dist/updates/update-retention-marker.d.ts +67 -0
  89. package/dist/updates/update-retention-marker.js +165 -0
  90. package/dist/updates/update-retention-plan.d.ts +25 -0
  91. package/dist/updates/update-retention-plan.js +54 -0
  92. package/dist/updates/update-retention-sync.d.ts +34 -0
  93. package/dist/updates/update-retention-sync.js +83 -0
  94. package/dist/updates/update-retirement.d.ts +205 -0
  95. package/dist/updates/update-retirement.js +1485 -0
  96. package/dist/updates/update-shutdown.d.ts +16 -4
  97. package/dist/updates/update-shutdown.js +133 -8
  98. package/dist/updates/update-state-store.d.ts +58 -0
  99. package/dist/updates/update-state-store.js +139 -0
  100. package/dist/updates/update-swap-stage.d.ts +1 -1
  101. package/dist/updates/update-swap-stage.js +85 -14
  102. package/dist/updates/update-swap.d.ts +45 -2
  103. package/dist/updates/update-swap.js +207 -17
  104. package/package.json +31 -1
  105. package/src/appearance/custom-theme-import.ts +96 -14
  106. package/src/appearance/custom-theme-library.ts +5 -0
  107. package/src/appearance/theme-record-adapter.ts +15 -6
  108. package/src/appearance/theme-registry.ts +8 -1
  109. package/src/desktop/client-asset-manifest.ts +207 -0
  110. package/src/desktop/client-asset-stream.ts +193 -32
  111. package/src/desktop/client-assets.ts +210 -19
  112. package/src/desktop/client-response-lifecycle.ts +305 -0
  113. package/src/native/electrobun-posix-launch-lease.patch +398 -0
  114. package/templates/application/README.md +50 -0
  115. package/templates/application/electrobun.config.ts +5 -1
  116. package/templates/application/scripts/build-desktop.ts +4 -0
  117. package/templates/application/src/bun/index.ts +173 -16
  118. package/templates/application/vite.config.ts +112 -6
@@ -0,0 +1,1485 @@
1
+ import { verifyReleaseDescriptor } from "./signed-release.js";
2
+ import { renameUpdateExclusive } from "./update-exclusive-rename.js";
3
+ import { readUpdateStageState, withUpdateLock, writeUpdateStageState } from "./update-state-store.js";
4
+ import { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, updateStagingFor } from "./update-swap.js";
5
+ import { readUpdateLaunchGate, tryAcquireUpdateHelperLiveness } from "./update-launch-gate.js";
6
+ import { hasUpdateHelperArtifacts } from "./update-helper.js";
7
+ import { tryAcquireUpdateGenerationLease } from "./update-generation-lease.js";
8
+ import { syncDarwinDescriptor } from "../native/darwin-sync.js";
9
+ import { removeDirectoryContentsChunk } from "../native/posix-tree-removal.js";
10
+ import { updateProcessMayBeAlive } from "./update-process-liveness.js";
11
+ import { planUpdateRetention, retentionIdentityKey } from "./update-retention-plan.js";
12
+ import { publishUpdateRetentionIntent, readUpdateRetentionIntent, readUpdateRetentionIntentFile, sameRetentionIntent, updateRetentionIntentPath } from "./update-retention-marker.js";
13
+ import { syncUpdateRetentionIntent } from "./update-retention-sync.js";
14
+ import { link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
15
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
16
+ import { constants as constants$1 } from "node:fs";
17
+ import { randomUUID } from "node:crypto";
18
+ // src/updates/update-retirement.ts
19
+ /** A failed promotion may have left the final marker in place; inspect before retrying. */
20
+ var UpdateRetentionOrphanPromotionError = class extends Error {
21
+ temporaryPath;
22
+ finalPath;
23
+ publicationState;
24
+ constructor(temporaryPath, finalPath, publicationState, cause) {
25
+ super("Update retention orphan promotion requires inspection", { cause });
26
+ this.temporaryPath = temporaryPath;
27
+ this.finalPath = finalPath;
28
+ this.publicationState = publicationState;
29
+ this.name = "UpdateRetentionOrphanPromotionError";
30
+ }
31
+ };
32
+ var VERSION = /^\d+\.\d+\.\d+(?:-dev\.\d+)?$/;
33
+ var UUID = /^[0-9a-f]{8}-[0-9a-f-]{27}$/i;
34
+ var PUBLISHER_TEMP_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
35
+ function hasExactOwnKeys(value, expected) {
36
+ const actual = Reflect.ownKeys(value);
37
+ return actual.length === expected.length && actual.every((key) => typeof key === "string" && expected.includes(key));
38
+ }
39
+ /** Generation-specific retirement paths, all beside the fixed staging path. */
40
+ function updateRetirementPaths(target, generation) {
41
+ if (typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || !UUID.test(generation)) throw new Error("Invalid update retirement identity");
42
+ const prefix = `.${basename(target)}.framework-retired-${generation}`;
43
+ const container = join(dirname(target), prefix);
44
+ return Object.freeze({
45
+ container,
46
+ tree: join(container, "tree"),
47
+ healthReceipt: join(container, "healthy.json"),
48
+ healthTemporaryPrefix: ".healthy-",
49
+ claim: join(dirname(target), `${prefix}.claim.json`),
50
+ claimTemporaryPrefix: `${prefix}.claim-`,
51
+ cleanupMarker: join(dirname(target), `.${basename(target)}.framework-update-cleanup.json`),
52
+ cleanupMarkerTemporaryPrefix: `.${basename(target)}.framework-update-cleanup-`
53
+ });
54
+ }
55
+ function retentionPruneProgressPath(target, generation) {
56
+ return `${updateRetirementPaths(target, generation).claim.slice(0, -11)}.prune-progress.json`;
57
+ }
58
+ function isPruneProgressName(name, target) {
59
+ const prefix = `.${basename(target)}.framework-retired-`;
60
+ if (!name.startsWith(prefix)) return false;
61
+ const suffix = name.slice(prefix.length);
62
+ const match = /^([0-9a-f-]{36})\.prune-progress\.json$/i.exec(suffix);
63
+ return Boolean(match && UUID.test(match[1]));
64
+ }
65
+ function pruneProgressNames(target, generation) {
66
+ return [basename(retentionPruneProgressPath(target, generation))];
67
+ }
68
+ function assertNoUnresolvedRetentionPruneArtifacts(target, names, allowances = {}, message = "An update retirement cleanup marker requires recovery") {
69
+ const pruneMarkerPrefix = `.${basename(target)}.framework-prune-`;
70
+ const pruneTemporaryPrefix = `..${basename(target)}.framework-prune-`;
71
+ const retirementPrefix = `.${basename(target)}.framework-retired-`;
72
+ const allowedRetentionIntentName = allowances.allowedRetentionIntentGeneration ? basename(updateRetentionIntentPath(target, allowances.allowedRetentionIntentGeneration)) : void 0;
73
+ const allowedProgressName = allowances.allowedPruneProgressGeneration ? pruneProgressNames(target, allowances.allowedPruneProgressGeneration)[0] : void 0;
74
+ if (names.some((name) => {
75
+ const foldedName = name.toLowerCase();
76
+ if (foldedName.startsWith(pruneMarkerPrefix.toLowerCase()) || foldedName.startsWith(pruneTemporaryPrefix.toLowerCase())) return name !== allowedRetentionIntentName && name !== allowances.allowedRetentionTemporaryName;
77
+ const foldedRetirementPrefix = retirementPrefix.toLowerCase();
78
+ return foldedName.startsWith(foldedRetirementPrefix) && foldedName.slice(foldedRetirementPrefix.length).includes("prune") && name !== allowedProgressName && name !== allowances.allowedPruneProgressTemporaryName;
79
+ })) throw new Error(message);
80
+ }
81
+ async function findPruneProgressTemporaryName(target, generation) {
82
+ const prefix = `${basename(retentionPruneProgressPath(target, generation))}.`;
83
+ const names = (await readdir(dirname(target))).filter((name) => name.startsWith(prefix) && name.endsWith(".tmp"));
84
+ if (names.length > 1) throw new Error("Multiple update retention progress temporaries require recovery");
85
+ const name = names[0];
86
+ if (!name) return void 0;
87
+ const temporaryId = name.slice(prefix.length, -4);
88
+ if (!UUID.test(temporaryId)) throw new Error("An update retention progress temporary requires recovery");
89
+ return name;
90
+ }
91
+ async function readPruneProgressFile(path, target, generation, expectedIntent, expectedOwner) {
92
+ try {
93
+ const canonicalPath = retentionPruneProgressPath(target, generation);
94
+ const canonicalName = basename(canonicalPath);
95
+ const pathName = basename(path);
96
+ const temporaryId = pathName.startsWith(`${canonicalName}.`) && pathName.endsWith(".tmp") ? pathName.slice(canonicalName.length + 1, -4) : "";
97
+ const canonicalTemporary = dirname(path) === dirname(canonicalPath) && UUID.test(temporaryId);
98
+ const info = await lstat(path);
99
+ if (path !== canonicalPath && !canonicalTemporary || !info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 8192) return void 0;
100
+ const value = JSON.parse(await readFile(path, "utf8"));
101
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
102
+ const record = value;
103
+ if (!hasExactOwnKeys(record, [
104
+ "schema",
105
+ "phase",
106
+ "intent",
107
+ "owner",
108
+ "healthReceipt"
109
+ ]) || record.schema !== 1 || record.phase !== "deleting" && record.phase !== "empty" || typeof record.intent !== "object" || record.intent === null || Array.isArray(record.intent) || !hasExactOwnKeys(record.intent, [
110
+ "schema",
111
+ "phase",
112
+ "target",
113
+ "generation",
114
+ "previousTreeIdentity",
115
+ "installedGeneration",
116
+ "installedTreeIdentity"
117
+ ]) || expectedIntent !== void 0 && !sameRetentionIntent(record.intent, expectedIntent) || typeof record.owner !== "object" || record.owner === null || Array.isArray(record.owner)) return void 0;
118
+ const intent = record.intent;
119
+ if (intent.schema !== 1 || intent.phase !== "prune-previous-tree" || typeof intent.target !== "string" || intent.target !== target || typeof intent.generation !== "string" || intent.generation !== generation.toLowerCase() || !retentionIdentityKey(intent.previousTreeIdentity) || !retentionIdentityKey(intent.installedTreeIdentity) || typeof intent.installedGeneration !== "string" || !UUID.test(intent.installedGeneration) || Object.keys(intent.previousTreeIdentity).length !== 2 || !hasExactOwnKeys(intent.previousTreeIdentity, ["device", "inode"]) || Object.keys(intent.installedTreeIdentity).length !== 2 || !hasExactOwnKeys(intent.installedTreeIdentity, ["device", "inode"])) return void 0;
120
+ const owner = parseOwner(record.owner);
121
+ if (!owner || expectedOwner && !ownerMatches(owner, expectedOwner)) return void 0;
122
+ const healthReceipt = parseHealthReceipt(record.healthReceipt);
123
+ if (owner.target !== target || owner.generation.toLowerCase() !== intent.generation || !sameUpdateTreeIdentity(intent.previousTreeIdentity, owner.previousTreeIdentity) || !healthReceiptMatches(healthReceipt, healthReceiptFor(owner)) || expectedIntent !== void 0 && !sameRetentionIntent(intent, expectedIntent)) return void 0;
124
+ return {
125
+ schema: 1,
126
+ phase: record.phase,
127
+ intent,
128
+ owner,
129
+ healthReceipt
130
+ };
131
+ } catch {
132
+ return;
133
+ }
134
+ }
135
+ async function publishPruneProgress(intent, owner, healthReceipt, phase) {
136
+ const path = retentionPruneProgressPath(intent.target, intent.generation);
137
+ const existing = await readPruneProgressFile(path, intent.target, intent.generation, intent, owner);
138
+ if (existing) {
139
+ if (!healthReceiptMatches(existing.healthReceipt, healthReceipt)) return false;
140
+ if (existing.phase === phase) return true;
141
+ if (existing.phase !== "deleting" || phase !== "empty") return false;
142
+ } else if (phase !== "deleting" || !healthReceiptMatches(healthReceipt, healthReceiptFor(owner)) || !healthReceiptMatches(await readHealthReceipt(updateRetirementPaths(intent.target, intent.generation).healthReceipt), healthReceipt)) return false;
143
+ const temporary = `${path}.${randomUUID()}.tmp`;
144
+ let publicationBarrierPassed = false;
145
+ try {
146
+ await writeFile(temporary, JSON.stringify({
147
+ schema: 1,
148
+ phase,
149
+ intent,
150
+ owner,
151
+ healthReceipt
152
+ }) + "\n", {
153
+ flag: "wx",
154
+ mode: 384
155
+ });
156
+ if (!await readPruneProgressFile(temporary, intent.target, intent.generation, intent, owner)) return false;
157
+ await syncPruneFile(temporary, intent.previousTreeIdentity.device);
158
+ if (existing) {
159
+ const before = await readPruneProgressFile(path, intent.target, intent.generation, intent, owner);
160
+ if (!before || before.phase !== "deleting") return false;
161
+ await rename(temporary, path);
162
+ await syncPruneDirectory(dirname(path), intent.previousTreeIdentity.device);
163
+ publicationBarrierPassed = true;
164
+ } else {
165
+ await link(temporary, path);
166
+ await syncPruneDirectory(dirname(path), intent.previousTreeIdentity.device);
167
+ publicationBarrierPassed = true;
168
+ await unlink(temporary);
169
+ await syncPruneDirectory(dirname(path), intent.previousTreeIdentity.device);
170
+ }
171
+ } catch {
172
+ if (!publicationBarrierPassed || await pathInfo(temporary)) return false;
173
+ return (await readPruneProgressFile(path, intent.target, intent.generation, intent, owner))?.phase === phase;
174
+ }
175
+ return (await readPruneProgressFile(path, intent.target, intent.generation, intent, owner))?.phase === phase;
176
+ }
177
+ async function readPruneProgress(target, generation, expectedIntent) {
178
+ return readPruneProgressFile(retentionPruneProgressPath(target, generation), target, generation, expectedIntent);
179
+ }
180
+ function sameFilesystemObject(left, right) {
181
+ return left.dev === right.dev && left.ino === right.ino;
182
+ }
183
+ async function syncPruneFile(path, expectedDevice) {
184
+ if (typeof constants$1.O_NOFOLLOW !== "number" || typeof constants$1.O_NONBLOCK !== "number") throw new Error("Update retention progress synchronization is unsupported on this platform");
185
+ const before = await lstat(path, { bigint: true });
186
+ if (!before.isFile() || before.isSymbolicLink() || expectedDevice !== void 0 && before.dev.toString() !== expectedDevice) throw new Error("Invalid update retention progress file before sync");
187
+ const file = await open(path, constants$1.O_RDONLY | constants$1.O_NOFOLLOW | constants$1.O_NONBLOCK);
188
+ try {
189
+ const opened = await file.stat({ bigint: true });
190
+ if (!opened.isFile() || !sameFilesystemObject(opened, before) || expectedDevice !== void 0 && opened.dev.toString() !== expectedDevice) throw new Error("Update retention progress file changed before sync");
191
+ syncDarwinDescriptor(file.fd, "file");
192
+ const synced = await file.stat({ bigint: true });
193
+ const after = await lstat(path, { bigint: true });
194
+ if (!synced.isFile() || !after.isFile() || after.isSymbolicLink() || !sameFilesystemObject(synced, opened) || !sameFilesystemObject(after, opened)) throw new Error("Update retention progress file changed during sync");
195
+ } finally {
196
+ await file.close();
197
+ }
198
+ }
199
+ async function syncPruneDirectory(path, expectedDevice) {
200
+ if (typeof constants$1.O_NOFOLLOW !== "number" || typeof constants$1.O_DIRECTORY !== "number") throw new Error("Update retention directory synchronization is unsupported on this platform");
201
+ const before = await lstat(path, { bigint: true });
202
+ if (!before.isDirectory() || before.isSymbolicLink() || expectedDevice !== void 0 && before.dev.toString() !== expectedDevice) throw new Error("Invalid update retention directory before sync");
203
+ const directory = await open(path, constants$1.O_RDONLY | constants$1.O_DIRECTORY | constants$1.O_NOFOLLOW);
204
+ try {
205
+ const opened = await directory.stat({ bigint: true });
206
+ if (!opened.isDirectory() || !sameFilesystemObject(opened, before) || expectedDevice !== void 0 && opened.dev.toString() !== expectedDevice) throw new Error("Update retention directory changed before sync");
207
+ syncDarwinDescriptor(directory.fd, "directory");
208
+ const synced = await directory.stat({ bigint: true });
209
+ const after = await lstat(path, { bigint: true });
210
+ if (!synced.isDirectory() || !after.isDirectory() || after.isSymbolicLink() || !sameFilesystemObject(synced, opened) || !sameFilesystemObject(after, opened)) throw new Error("Update retention directory changed during sync");
211
+ } finally {
212
+ await directory.close();
213
+ }
214
+ }
215
+ async function syncPruneRecoveryEvidence(target, intent, inventory) {
216
+ const expectedDevice = intent.previousTreeIdentity.device;
217
+ if (intent.installedTreeIdentity.device !== expectedDevice || inventory.actualIdentity.device !== expectedDevice) throw new Error("Update retention recovery evidence crosses a filesystem boundary");
218
+ const installedOwner = inventory.records.find(({ owner }) => owner.generation.toLowerCase() === intent.installedGeneration.toLowerCase())?.owner;
219
+ if (!installedOwner || installedOwner.newVersion !== inventory.actualVersion || !sameUpdateTreeIdentity(installedOwner.newTreeIdentity, inventory.actualIdentity)) throw new Error("Update retention installed lineage changed before synchronization");
220
+ const versionPath = join(target, ...process.platform === "darwin" ? ["Contents", "Resources"] : ["Resources"], "version.json");
221
+ await syncPruneFile(versionPath, expectedDevice);
222
+ await syncPruneDirectory(dirname(versionPath), expectedDevice);
223
+ await syncPruneDirectory(target, expectedDevice);
224
+ for (const { owner, paths, healthy } of inventory.records) {
225
+ if (!healthy || owner.previousTreeIdentity.device !== expectedDevice || owner.newTreeIdentity.device !== expectedDevice) throw new Error("Update retention record is not complete recovery evidence");
226
+ const claimOwner = await readOwner(paths.claim);
227
+ const receipt = await readHealthReceipt(paths.healthReceipt);
228
+ if (!ownerMatches(claimOwner, owner) || !healthReceiptMatches(receipt, healthReceiptFor(owner))) throw new Error("Update retention recovery evidence changed before synchronization");
229
+ await syncPruneFile(paths.claim, expectedDevice);
230
+ await syncPruneFile(paths.healthReceipt, expectedDevice);
231
+ await syncPruneDirectory(paths.container, expectedDevice);
232
+ }
233
+ await syncPruneDirectory(dirname(target), expectedDevice);
234
+ }
235
+ async function syncPruneProgress(target, generation, expected) {
236
+ const path = retentionPruneProgressPath(target, generation);
237
+ const before = await readPruneProgressFile(path, target, generation, expected.intent, expected.owner);
238
+ if (!before || before.phase !== expected.phase || !healthReceiptMatches(before.healthReceipt, expected.healthReceipt)) throw new Error("Update retention progress changed before synchronization");
239
+ await syncPruneFile(path, expected.intent.previousTreeIdentity.device);
240
+ await syncPruneDirectory(dirname(path), expected.intent.previousTreeIdentity.device);
241
+ const after = await readPruneProgressFile(path, target, generation, expected.intent, expected.owner);
242
+ if (!after || after.phase !== expected.phase || !healthReceiptMatches(after.healthReceipt, expected.healthReceipt)) throw new Error("Update retention progress changed during synchronization");
243
+ }
244
+ async function matchesPartiallyPrunedContainer(intent, owner, paths, phase) {
245
+ if (intent.generation !== owner.generation.toLowerCase() || intent.target !== owner.target || !sameUpdateTreeIdentity(intent.previousTreeIdentity, owner.previousTreeIdentity)) return false;
246
+ const containerInfo = await pathInfo(paths.container);
247
+ if (!containerInfo) return phase === "empty" && !await pathInfo(paths.tree);
248
+ if (!containerInfo.isDirectory() || containerInfo.isSymbolicLink()) return false;
249
+ const entries = await readdir(paths.container);
250
+ const treeInfo = await pathInfo(paths.tree);
251
+ const healthInfo = await pathInfo(paths.healthReceipt);
252
+ const allowed = /* @__PURE__ */ new Set([...treeInfo ? ["tree"] : [], ...healthInfo ? ["healthy.json"] : []]);
253
+ if (entries.length !== allowed.size || entries.some((name) => !allowed.has(name))) return false;
254
+ if (!treeInfo) return phase === "empty";
255
+ if (!treeInfo.isDirectory() || treeInfo.isSymbolicLink() || !await samePathTreeIdentity(paths.tree, intent.previousTreeIdentity)) return false;
256
+ if (phase === "empty") return (await readdir(paths.tree)).length === 0;
257
+ return true;
258
+ }
259
+ async function samePathTreeIdentity(path, identity) {
260
+ try {
261
+ return sameUpdateTreeIdentity(await readUpdateTreeIdentity(path), identity);
262
+ } catch {
263
+ return false;
264
+ }
265
+ }
266
+ function ownerFor(target, state) {
267
+ if (!state.previousTreeIdentity || !state.candidateTreeIdentity) return void 0;
268
+ const paths = updateRetirementPaths(target, state.generation);
269
+ return {
270
+ schema: 2,
271
+ generation: state.generation,
272
+ target,
273
+ newVersion: state.version,
274
+ previousVersion: state.previousVersion,
275
+ previousTreeIdentity: state.previousTreeIdentity,
276
+ newTreeIdentity: state.candidateTreeIdentity,
277
+ container: basename(paths.container),
278
+ tree: "tree"
279
+ };
280
+ }
281
+ function parseOwner(value) {
282
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
283
+ const record = value;
284
+ const identity = record.previousTreeIdentity;
285
+ const newTreeIdentity = record.newTreeIdentity;
286
+ if (record.schema !== 2 || typeof record.generation !== "string" || !UUID.test(record.generation) || typeof record.target !== "string" || !isAbsolute(record.target) || resolve(record.target) !== record.target || typeof record.newVersion !== "string" || !VERSION.test(record.newVersion) || typeof record.previousVersion !== "string" || !VERSION.test(record.previousVersion) || typeof identity !== "object" || identity === null || Array.isArray(identity) || !hasExactOwnKeys(identity, ["device", "inode"]) || typeof identity.device !== "string" || !/^[1-9]\d{0,19}$/.test(identity.device) || typeof identity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(identity.inode) || typeof newTreeIdentity !== "object" || newTreeIdentity === null || Array.isArray(newTreeIdentity) || !hasExactOwnKeys(newTreeIdentity, ["device", "inode"]) || typeof newTreeIdentity.device !== "string" || !/^[1-9]\d{0,19}$/.test(newTreeIdentity.device) || typeof newTreeIdentity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(newTreeIdentity.inode) || typeof record.container !== "string" || record.container !== `.${basename(record.target)}.framework-retired-${record.generation}` || record.tree !== "tree" || !hasExactOwnKeys(record, [
287
+ "schema",
288
+ "generation",
289
+ "target",
290
+ "newVersion",
291
+ "previousVersion",
292
+ "previousTreeIdentity",
293
+ "newTreeIdentity",
294
+ "container",
295
+ "tree"
296
+ ])) return void 0;
297
+ return record;
298
+ }
299
+ function ownerMatches(actual, expected) {
300
+ return actual !== void 0 && actual.schema === expected.schema && actual.generation === expected.generation && actual.target === expected.target && actual.newVersion === expected.newVersion && actual.previousVersion === expected.previousVersion && actual.container === expected.container && actual.tree === expected.tree && sameUpdateTreeIdentity(actual.previousTreeIdentity, expected.previousTreeIdentity) && sameUpdateTreeIdentity(actual.newTreeIdentity, expected.newTreeIdentity);
301
+ }
302
+ function cleanupMarkerFor(target, state) {
303
+ const paths = updateRetirementPaths(target, state.generation);
304
+ return {
305
+ schema: 1,
306
+ generation: state.generation,
307
+ target,
308
+ version: state.version,
309
+ claim: basename(paths.claim),
310
+ phase: "staging-cleanup"
311
+ };
312
+ }
313
+ function cleanupMarkerMatches(actual, expected) {
314
+ return actual !== void 0 && actual.schema === expected.schema && actual.generation === expected.generation && actual.target === expected.target && actual.version === expected.version && actual.claim === expected.claim && actual.phase === expected.phase;
315
+ }
316
+ function parseCleanupMarker(value) {
317
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
318
+ const record = value;
319
+ if (record.schema !== 1 || typeof record.generation !== "string" || !UUID.test(record.generation) || typeof record.target !== "string" || !isAbsolute(record.target) || resolve(record.target) !== record.target || typeof record.version !== "string" || !VERSION.test(record.version) || typeof record.claim !== "string" || record.claim !== basename(updateRetirementPaths(record.target, record.generation).claim) || record.phase !== "staging-cleanup" || Object.keys(record).length !== 6) return void 0;
320
+ return record;
321
+ }
322
+ async function readOwner(path) {
323
+ try {
324
+ const info = await lstat(path);
325
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096) return void 0;
326
+ return parseOwner(JSON.parse(await readFile(path, "utf8")));
327
+ } catch {
328
+ return;
329
+ }
330
+ }
331
+ function parseHealthReceipt(value) {
332
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
333
+ const record = value;
334
+ const identity = record.treeIdentity;
335
+ if (record.schema !== 1 || typeof record.generation !== "string" || !UUID.test(record.generation) || typeof record.target !== "string" || !isAbsolute(record.target) || resolve(record.target) !== record.target || typeof record.version !== "string" || !VERSION.test(record.version) || typeof identity !== "object" || identity === null || Array.isArray(identity) || !hasExactOwnKeys(identity, ["device", "inode"]) || typeof identity.device !== "string" || !/^[1-9]\d{0,19}$/.test(identity.device) || typeof identity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(identity.inode) || !hasExactOwnKeys(record, [
336
+ "schema",
337
+ "generation",
338
+ "target",
339
+ "version",
340
+ "treeIdentity"
341
+ ])) return void 0;
342
+ return record;
343
+ }
344
+ async function readHealthReceipt(path) {
345
+ try {
346
+ const info = await lstat(path);
347
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096) return void 0;
348
+ return parseHealthReceipt(JSON.parse(await readFile(path, "utf8")));
349
+ } catch {
350
+ return;
351
+ }
352
+ }
353
+ function healthReceiptFor(owner) {
354
+ return {
355
+ schema: 1,
356
+ generation: owner.generation,
357
+ target: owner.target,
358
+ version: owner.newVersion,
359
+ treeIdentity: owner.newTreeIdentity
360
+ };
361
+ }
362
+ function healthReceiptMatches(actual, expected) {
363
+ return actual !== void 0 && actual.schema === expected.schema && actual.generation === expected.generation && actual.target === expected.target && actual.version === expected.version && sameUpdateTreeIdentity(actual.treeIdentity, expected.treeIdentity);
364
+ }
365
+ async function readCleanupMarker(path) {
366
+ try {
367
+ const info = await lstat(path);
368
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096) return void 0;
369
+ return parseCleanupMarker(JSON.parse(await readFile(path, "utf8")));
370
+ } catch {
371
+ return;
372
+ }
373
+ }
374
+ async function pathInfo(path) {
375
+ try {
376
+ return await lstat(path);
377
+ } catch (error) {
378
+ if (error.code === "ENOENT") return void 0;
379
+ throw error;
380
+ }
381
+ }
382
+ async function matchesOldTree(path, state) {
383
+ if (!state.previousTreeIdentity) return false;
384
+ try {
385
+ const info = await lstat(path);
386
+ return info.isDirectory() && !info.isSymbolicLink() && await readUpdateTreeVersion(path) === state.previousVersion && sameUpdateTreeIdentity(await readUpdateTreeIdentity(path), state.previousTreeIdentity);
387
+ } catch {
388
+ return false;
389
+ }
390
+ }
391
+ function isMatchingClaimTemporary(name, paths) {
392
+ if (!name.startsWith(paths.claimTemporaryPrefix) || !name.endsWith(".tmp")) return false;
393
+ return UUID.test(name.slice(paths.claimTemporaryPrefix.length, -4));
394
+ }
395
+ /**
396
+ * Publish the generation claim from a complete private temporary using an
397
+ * exclusive rename. A valid interrupted temporary can be promoted on retry;
398
+ * malformed or colliding files are preserved and never treated as ownership.
399
+ */
400
+ async function ensureClaim(target, state) {
401
+ const expected = ownerFor(target, state);
402
+ if (!expected) return false;
403
+ const paths = updateRetirementPaths(target, state.generation);
404
+ if (await pathInfo(paths.claim)) return ownerMatches(await readOwner(paths.claim), expected);
405
+ let entries;
406
+ try {
407
+ entries = await readdir(dirname(target));
408
+ } catch {
409
+ return false;
410
+ }
411
+ const temporaryNames = entries.filter((name) => isMatchingClaimTemporary(name, paths));
412
+ for (const name of temporaryNames) {
413
+ const temporary = join(dirname(target), name);
414
+ const info = await pathInfo(temporary);
415
+ if (!info || !info.isFile() || info.isSymbolicLink()) continue;
416
+ if (!ownerMatches(await readOwner(temporary), expected)) continue;
417
+ try {
418
+ renameUpdateExclusive(temporary, paths.claim);
419
+ } catch {
420
+ return ownerMatches(await readOwner(paths.claim), expected);
421
+ }
422
+ return ownerMatches(await readOwner(paths.claim), expected);
423
+ }
424
+ const temporary = join(dirname(target), `${paths.claimTemporaryPrefix}${randomUUID()}.tmp`);
425
+ try {
426
+ await writeFile(temporary, JSON.stringify(expected) + "\n", {
427
+ flag: "wx",
428
+ mode: 384
429
+ });
430
+ if (!ownerMatches(await readOwner(temporary), expected)) return false;
431
+ renameUpdateExclusive(temporary, paths.claim);
432
+ } catch {
433
+ return ownerMatches(await readOwner(paths.claim), expected);
434
+ }
435
+ return ownerMatches(await readOwner(paths.claim), expected);
436
+ }
437
+ function isMatchingCleanupTemporary(name, paths) {
438
+ if (!name.startsWith(paths.cleanupMarkerTemporaryPrefix) || !name.endsWith(".tmp")) return false;
439
+ return UUID.test(name.slice(paths.cleanupMarkerTemporaryPrefix.length, -4));
440
+ }
441
+ async function ensureCleanupMarker(target, state) {
442
+ const expected = cleanupMarkerFor(target, state);
443
+ const paths = updateRetirementPaths(target, state.generation);
444
+ if (await pathInfo(paths.cleanupMarker)) return cleanupMarkerMatches(await readCleanupMarker(paths.cleanupMarker), expected);
445
+ let entries;
446
+ try {
447
+ entries = await readdir(dirname(target));
448
+ } catch {
449
+ return false;
450
+ }
451
+ for (const name of entries.filter((entry) => isMatchingCleanupTemporary(entry, paths))) {
452
+ const temporary = join(dirname(target), name);
453
+ const info = await pathInfo(temporary);
454
+ if (!info?.isFile() || info.isSymbolicLink()) continue;
455
+ if (!cleanupMarkerMatches(await readCleanupMarker(temporary), expected)) continue;
456
+ try {
457
+ renameUpdateExclusive(temporary, paths.cleanupMarker);
458
+ } catch {
459
+ return cleanupMarkerMatches(await readCleanupMarker(paths.cleanupMarker), expected);
460
+ }
461
+ return cleanupMarkerMatches(await readCleanupMarker(paths.cleanupMarker), expected);
462
+ }
463
+ const temporary = join(dirname(target), `${paths.cleanupMarkerTemporaryPrefix}${randomUUID()}.tmp`);
464
+ try {
465
+ await writeFile(temporary, JSON.stringify(expected) + "\n", {
466
+ flag: "wx",
467
+ mode: 384
468
+ });
469
+ if (!cleanupMarkerMatches(await readCleanupMarker(temporary), expected)) return false;
470
+ renameUpdateExclusive(temporary, paths.cleanupMarker);
471
+ } catch {
472
+ return cleanupMarkerMatches(await readCleanupMarker(paths.cleanupMarker), expected);
473
+ }
474
+ return cleanupMarkerMatches(await readCleanupMarker(paths.cleanupMarker), expected);
475
+ }
476
+ async function matchesOwnedTree(path, owner) {
477
+ try {
478
+ const info = await lstat(path);
479
+ return info.isDirectory() && !info.isSymbolicLink() && await readUpdateTreeVersion(path) === owner.previousVersion && sameUpdateTreeIdentity(await readUpdateTreeIdentity(path), owner.previousTreeIdentity);
480
+ } catch {
481
+ return false;
482
+ }
483
+ }
484
+ async function matchesInstalledTree(path, owner) {
485
+ try {
486
+ const info = await lstat(path);
487
+ return info.isDirectory() && !info.isSymbolicLink() && await readUpdateTreeVersion(path) === owner.newVersion && sameUpdateTreeIdentity(await readUpdateTreeIdentity(path), owner.newTreeIdentity);
488
+ } catch {
489
+ return false;
490
+ }
491
+ }
492
+ function isMatchingHealthTemporary(name) {
493
+ return name.startsWith(".healthy-") && name.endsWith(".tmp") && UUID.test(name.slice(9, -4));
494
+ }
495
+ async function validRetirementContainer(owner, paths, allowHealthTemporaries = true, pruneProgress) {
496
+ const info = await pathInfo(paths.container);
497
+ if (!info?.isDirectory() || info.isSymbolicLink()) return false;
498
+ if (pruneProgress) {
499
+ if (!await matchesPartiallyPrunedContainer(pruneProgress.intent, owner, paths, pruneProgress.phase)) return false;
500
+ } else if (!await matchesOwnedTree(paths.tree, owner)) return false;
501
+ const entries = await readdir(paths.container);
502
+ if (entries.some((name) => name !== "tree" && name !== "healthy.json" && !isMatchingHealthTemporary(name))) return false;
503
+ if (!allowHealthTemporaries && entries.some(isMatchingHealthTemporary)) return false;
504
+ const receiptInfo = await pathInfo(paths.healthReceipt);
505
+ if (receiptInfo) {
506
+ const receipt = await readHealthReceipt(paths.healthReceipt);
507
+ if (!receiptInfo.isFile() || receiptInfo.isSymbolicLink() || !receipt) return false;
508
+ if (!healthReceiptMatches(receipt, healthReceiptFor(owner))) return false;
509
+ }
510
+ for (const name of entries.filter(isMatchingHealthTemporary)) {
511
+ const temporaryInfo = await pathInfo(join(paths.container, name));
512
+ if (!temporaryInfo?.isFile() || temporaryInfo.isSymbolicLink() || temporaryInfo.size > 4096) return false;
513
+ const receipt = await readHealthReceipt(join(paths.container, name));
514
+ if (receipt && !healthReceiptMatches(receipt, healthReceiptFor(owner))) return false;
515
+ }
516
+ return true;
517
+ }
518
+ function generationFromClaimName(name, target) {
519
+ const prefix = `.${basename(target)}.framework-retired-`;
520
+ if (!name.startsWith(prefix) || !name.endsWith(".claim.json")) return void 0;
521
+ const generation = name.slice(prefix.length, -11);
522
+ return UUID.test(generation) ? generation : void 0;
523
+ }
524
+ /**
525
+ * Read and validate every retirement claim and container while the install lock
526
+ * is held. Retention planning can opt into rejecting in-progress cleanup and
527
+ * receipt publication artifacts; acknowledgement discovery preserves its
528
+ * existing support for those recoverable receipt temporaries.
529
+ */
530
+ async function readValidatedRetirementInventoryWhileLocked(target, currentVersion, options = {}) {
531
+ const strictRetentionState = options.strictRetentionState === true;
532
+ const targetInfo = await pathInfo(target);
533
+ const actualVersion = targetInfo?.isDirectory() ? await readUpdateTreeVersion(target) : void 0;
534
+ const actualIdentity = targetInfo?.isDirectory() ? await readUpdateTreeIdentity(target) : void 0;
535
+ if (!targetInfo?.isDirectory() || targetInfo.isSymbolicLink() || actualVersion !== currentVersion || !actualIdentity) throw new Error("The installed update does not match the host version");
536
+ const names = await readdir(dirname(target));
537
+ const retirementPrefix = `.${basename(target)}.framework-retired-`;
538
+ const cleanupMarkerName = `.${basename(target)}.framework-update-cleanup.json`;
539
+ const cleanupTemporaryPrefix = `.${basename(target)}.framework-update-cleanup-`;
540
+ const progressNames = names.filter((name) => isPruneProgressName(name, target));
541
+ let pruneProgress;
542
+ let pruneProgressTemporary;
543
+ let pruneIntentOnDisk;
544
+ if (progressNames.length > 0) {
545
+ const generation = options.allowedPruneProgressGeneration;
546
+ if (!generation || progressNames.some((name) => !pruneProgressNames(target, generation).includes(name))) throw new Error("A partial update retention prune requires recovery");
547
+ const progressTemporaryPrefix = `${basename(retentionPruneProgressPath(target, generation))}.`;
548
+ pruneIntentOnDisk = await readUpdateRetentionIntent(target, generation);
549
+ pruneProgress = await readPruneProgress(target, generation, pruneIntentOnDisk);
550
+ if (!pruneProgress) throw new Error("An update retention progress marker requires recovery");
551
+ if (!pruneIntentOnDisk && pruneProgress.phase !== "empty") throw new Error("A partial update retention prune lost its intent");
552
+ const progressTemporaries = names.filter((name) => name.startsWith(progressTemporaryPrefix) && name.endsWith(".tmp"));
553
+ if (progressTemporaries.length > 0) {
554
+ const temporaryName = options.allowedPruneProgressTemporaryName;
555
+ if (progressTemporaries.length !== 1 || !temporaryName || progressTemporaries[0] !== temporaryName || !UUID.test(temporaryName.slice(progressTemporaryPrefix.length, -4))) throw new Error("An update retention progress publication requires recovery");
556
+ pruneProgressTemporary = await readPruneProgressFile(join(dirname(target), temporaryName), target, generation, pruneIntentOnDisk, pruneProgress.owner);
557
+ const [finalInfo, temporaryInfo] = await Promise.all([lstat(retentionPruneProgressPath(target, generation), { bigint: true }), lstat(join(dirname(target), temporaryName), { bigint: true })]);
558
+ const sameHardLink = finalInfo.dev === temporaryInfo.dev && finalInfo.ino === temporaryInfo.ino;
559
+ const duplicatePublication = pruneProgressTemporary !== void 0 && sameHardLink && pruneProgressTemporary.phase === pruneProgress.phase && healthReceiptMatches(pruneProgressTemporary.healthReceipt, pruneProgress.healthReceipt);
560
+ const interruptedPhaseTransition = pruneProgressTemporary !== void 0 && !sameHardLink && pruneProgress.phase === "deleting" && pruneProgressTemporary.phase === "empty" && healthReceiptMatches(pruneProgressTemporary.healthReceipt, pruneProgress.healthReceipt) && await matchesPartiallyPrunedContainer(pruneProgressTemporary.intent, pruneProgressTemporary.owner, updateRetirementPaths(target, generation), "empty");
561
+ if (!duplicatePublication && !interruptedPhaseTransition) throw new Error("An update retention progress temporary is ambiguous");
562
+ } else if (options.allowedPruneProgressTemporaryName !== void 0) throw new Error("An update retention progress temporary disappeared");
563
+ } else if (options.allowedPruneProgressGeneration !== void 0) {
564
+ const generation = options.allowedPruneProgressGeneration;
565
+ const temporaryName = options.allowedPruneProgressTemporaryName;
566
+ const progressTemporaryPrefix = `${basename(retentionPruneProgressPath(target, generation))}.`;
567
+ const progressTemporaries = names.filter((name) => name.startsWith(progressTemporaryPrefix) && name.endsWith(".tmp"));
568
+ if (!temporaryName || progressTemporaries.length !== 1 || progressTemporaries[0] !== temporaryName || !UUID.test(temporaryName.slice(progressTemporaryPrefix.length, -4))) throw new Error("An update retention progress marker disappeared");
569
+ pruneIntentOnDisk = await readUpdateRetentionIntent(target, generation);
570
+ pruneProgressTemporary = await readPruneProgressFile(join(dirname(target), temporaryName), target, generation, pruneIntentOnDisk);
571
+ if (!pruneIntentOnDisk || !pruneProgressTemporary || pruneProgressTemporary.phase !== "deleting") throw new Error("An orphaned update retention progress temporary requires recovery");
572
+ } else if (options.allowedPruneProgressTemporaryName !== void 0) throw new Error("An update retention progress marker disappeared");
573
+ const allowedRetentionIntentName = options.allowedRetentionIntentGeneration ? basename(updateRetentionIntentPath(target, options.allowedRetentionIntentGeneration)) : void 0;
574
+ if (strictRetentionState && names.some((name) => {
575
+ const foldedName = name.toLowerCase();
576
+ return foldedName === cleanupMarkerName.toLowerCase() || foldedName.startsWith(cleanupTemporaryPrefix.toLowerCase());
577
+ })) throw new Error("An update retirement cleanup marker requires recovery");
578
+ if (strictRetentionState) assertNoUnresolvedRetentionPruneArtifacts(target, names, options);
579
+ const claimNames = /* @__PURE__ */ new Set();
580
+ const containerGenerations = /* @__PURE__ */ new Set();
581
+ for (const name of names.filter((entry) => entry.startsWith(retirementPrefix))) {
582
+ if (isPruneProgressName(name, target)) continue;
583
+ if (name === options.allowedPruneProgressTemporaryName) continue;
584
+ const suffix = name.slice(retirementPrefix.length);
585
+ if (UUID.test(suffix)) {
586
+ const containerInfo = await pathInfo(join(dirname(target), name));
587
+ if (!containerInfo?.isDirectory() || containerInfo.isSymbolicLink()) throw new Error("An update retirement container requires recovery");
588
+ containerGenerations.add(suffix);
589
+ continue;
590
+ }
591
+ if (generationFromClaimName(name, target)) {
592
+ claimNames.add(name);
593
+ continue;
594
+ }
595
+ if (suffix.endsWith(".claim.json")) throw new Error("An update retirement claim has an invalid generation");
596
+ const generation = suffix.slice(0, 36);
597
+ const claimTemporaryId = suffix.startsWith(`${generation}.claim-`) && suffix.endsWith(".tmp") ? suffix.slice(generation.length + 7, -4) : "";
598
+ if (UUID.test(generation) && UUID.test(claimTemporaryId)) throw new Error("An update retirement claim publication is incomplete");
599
+ throw new Error("An unknown update retirement entry requires recovery");
600
+ }
601
+ for (const generation of containerGenerations) if (!claimNames.has(basename(updateRetirementPaths(target, generation).claim)) && generation.toLowerCase() !== pruneProgress?.intent.generation) throw new Error("An update retirement container has no matching claim");
602
+ const records = [];
603
+ for (const name of claimNames) {
604
+ const generation = generationFromClaimName(name, target);
605
+ if (!generation) {
606
+ if (name.endsWith(".claim.json")) throw new Error("An update retirement claim has an invalid generation");
607
+ continue;
608
+ }
609
+ const paths = updateRetirementPaths(target, generation);
610
+ if (name !== basename(paths.claim)) continue;
611
+ if (pruneProgress?.intent.generation === generation.toLowerCase()) continue;
612
+ const claimInfo = await pathInfo(paths.claim);
613
+ const owner = await readOwner(paths.claim);
614
+ if (!claimInfo?.isFile() || claimInfo.isSymbolicLink() || !owner || owner.target !== target || owner.generation !== generation) throw new Error("An update retirement claim requires recovery");
615
+ const recordProgress = pruneProgress && owner.generation.toLowerCase() === pruneProgress.intent.generation ? pruneProgress : void 0;
616
+ if (recordProgress && !ownerMatches(owner, recordProgress.owner) || !await validRetirementContainer(owner, paths, !strictRetentionState, recordProgress)) throw new Error("An update retirement container requires recovery");
617
+ records.push({
618
+ owner,
619
+ paths,
620
+ healthy: Boolean(await pathInfo(paths.healthReceipt))
621
+ });
622
+ }
623
+ if (pruneProgressTemporary && !pruneProgress) {
624
+ const record = records.find(({ owner }) => owner.generation.toLowerCase() === pruneProgressTemporary.intent.generation);
625
+ if (!record || !ownerMatches(record.owner, pruneProgressTemporary.owner) || !healthReceiptMatches(await readHealthReceipt(record.paths.healthReceipt), pruneProgressTemporary.healthReceipt)) throw new Error("An orphaned update retention progress temporary is stale");
626
+ }
627
+ if (pruneProgress) {
628
+ const owner = pruneProgress.owner;
629
+ const paths = updateRetirementPaths(target, owner.generation);
630
+ const installedOwner = records.find(({ owner: recordOwner }) => recordOwner.generation.toLowerCase() === pruneProgress.intent.installedGeneration)?.owner;
631
+ if (owner.target !== target || owner.generation.toLowerCase() !== pruneProgress.intent.generation || pruneProgress.intent.target !== target || !sameUpdateTreeIdentity(pruneProgress.intent.installedTreeIdentity, actualIdentity) || !installedOwner || installedOwner.newVersion !== actualVersion || !sameUpdateTreeIdentity(installedOwner.newTreeIdentity, actualIdentity) || !await matchesInstalledTree(target, installedOwner) || !await matchesPartiallyPrunedContainer(pruneProgress.intent, owner, paths, pruneProgress.phase)) throw new Error("An update retention prune no longer matches its installed generation");
632
+ const claimInfo = await pathInfo(paths.claim);
633
+ if (pruneProgress.phase === "deleting" && !claimInfo) throw new Error("A partial update retention prune lost its claim");
634
+ if (claimInfo) {
635
+ if (!claimInfo.isFile() || claimInfo.isSymbolicLink()) throw new Error("An update retention prune claim changed during recovery");
636
+ const claimOwner = await readOwner(paths.claim);
637
+ if (!claimOwner || !ownerMatches(claimOwner, owner)) throw new Error("An update retention prune claim changed during recovery");
638
+ }
639
+ if (pruneProgress.phase === "deleting" && !pruneIntentOnDisk) throw new Error("A partial update retention prune lost its intent");
640
+ const healthInfo = await pathInfo(paths.healthReceipt);
641
+ if (pruneProgress.phase === "deleting" && !healthInfo) throw new Error("A partial update retention prune lost its health receipt");
642
+ if (healthInfo) {
643
+ const receipt = await readHealthReceipt(paths.healthReceipt);
644
+ if (!healthInfo.isFile() || healthInfo.isSymbolicLink() || !healthReceiptMatches(receipt, pruneProgress.healthReceipt)) throw new Error("An update retention prune health receipt changed during recovery");
645
+ }
646
+ records.push({
647
+ owner,
648
+ paths,
649
+ healthy: true
650
+ });
651
+ }
652
+ return {
653
+ actualVersion,
654
+ actualIdentity,
655
+ records,
656
+ allowedIntentObserved: allowedRetentionIntentName !== void 0 && names.includes(allowedRetentionIntentName)
657
+ };
658
+ }
659
+ /**
660
+ * Discover the exact unacknowledged installed generation after staging cleanup.
661
+ * The generation claim is persistent beside the retired tree, so discovery does
662
+ * not depend on a startup return value or log message.
663
+ */
664
+ async function findPendingUpdateHealthAcknowledgement(options) {
665
+ const { target, currentVersion } = options;
666
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update health acknowledgement lookup");
667
+ return withUpdateLock(target, async () => {
668
+ const staging = updateStagingFor(target);
669
+ const stagingInfo = await pathInfo(staging);
670
+ if (stagingInfo) {
671
+ if (!stagingInfo.isDirectory() || stagingInfo.isSymbolicLink()) return null;
672
+ const state = await readUpdateStageState(staging);
673
+ if (state?.helperPid && updateProcessMayBeAlive(state.helperPid)) return null;
674
+ if ((!state || !state.helperPid) && await hasUpdateHelperArtifacts(staging)) return null;
675
+ }
676
+ const inventory = await readValidatedRetirementInventoryWhileLocked(target, currentVersion);
677
+ const pending = [];
678
+ for (const record of inventory.records) {
679
+ const { owner } = record;
680
+ if (owner.newVersion !== inventory.actualVersion || !sameUpdateTreeIdentity(owner.newTreeIdentity, inventory.actualIdentity)) continue;
681
+ if (!await matchesInstalledTree(target, owner)) throw new Error("An installed update retirement record requires recovery");
682
+ if (!record.healthy) pending.push({
683
+ generation: owner.generation,
684
+ version: owner.newVersion
685
+ });
686
+ }
687
+ if (pending.length > 1) throw new Error("Multiple update generations match the installed tree");
688
+ return pending[0] ?? null;
689
+ });
690
+ }
691
+ /**
692
+ * Fail closed before publishing a new stage while any retention-prune intent,
693
+ * progress marker, temporary, or unknown prune-shaped artifact is present.
694
+ * Uses the same artifact-name check as strict retention inventory and must be
695
+ * called while the per-install update lock is held. It deliberately does not
696
+ * require unrelated retirement history to be valid before a new stage.
697
+ */
698
+ async function assertNoUpdateRetentionPruneArtifactsWhileLocked(target) {
699
+ if (typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || target.includes("\0") || !basename(target)) throw new Error("Invalid update retention prune gate target");
700
+ assertNoUnresolvedRetentionPruneArtifacts(target, await readdir(dirname(target)), {}, "update retention prune requires recovery before staging");
701
+ }
702
+ /**
703
+ * Plan rollback-tree retention from a complete, read-only filesystem inventory.
704
+ * This does not delete or modify retirement records; callers must revalidate
705
+ * ownership and the returned plan before any future cleanup operation.
706
+ */
707
+ async function planValidatedUpdateRetention(options) {
708
+ const { target, currentVersion } = options;
709
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
710
+ return withUpdateLock(target, async () => (await planRetentionWhileLocked(target, currentVersion)).plan);
711
+ }
712
+ async function planRetentionWhileLocked(target, currentVersion, options = {}) {
713
+ const staging = updateStagingFor(target);
714
+ if (await pathInfo(staging)) {
715
+ if (!options.validatedStagedVersion || !options.stagedTrust) throw new Error("An update staging directory requires recovery");
716
+ const stagedTrust = options.stagedTrust;
717
+ const info = await pathInfo(staging);
718
+ const state = await readUpdateStageState(staging);
719
+ const descriptor = state?.signedRelease ? verifyReleaseDescriptor(state.signedRelease, stagedTrust) : { ok: false };
720
+ const candidate = join(staging, "candidate");
721
+ const [targetVersion, candidateVersion, targetIdentity, candidateIdentity] = await Promise.all([
722
+ readUpdateTreeVersion(target),
723
+ readUpdateTreeVersion(candidate),
724
+ readUpdateTreeIdentity(target),
725
+ readUpdateTreeIdentity(candidate)
726
+ ]);
727
+ if (!info?.isDirectory() || info.isSymbolicLink() || !state || state.phase !== "staged" || state.version !== options.validatedStagedVersion || state.previousVersion !== currentVersion || state.helperPid !== void 0 || state.helperOwner !== void 0 || state.launchGateOwner !== void 0 || !state.candidateTreeDigest || !descriptor.ok || descriptor.descriptor.version !== state.version || descriptor.descriptor.channel !== stagedTrust.channel || await readUpdateLaunchGate(target) || await hasUpdateHelperArtifacts(staging) || await pathInfo(join(staging, "old")) || targetVersion !== currentVersion || candidateVersion !== state.version || state.previousTreeIdentity !== void 0 && !sameUpdateTreeIdentity(targetIdentity, state.previousTreeIdentity) || !sameUpdateTreeIdentity(candidateIdentity, state.candidateTreeIdentity) || !sameUpdateTreeDigest(await readUpdateTreeDigest(candidate), state.candidateTreeDigest)) throw new Error("A staged update changed before retained tree acquisition");
728
+ }
729
+ const inventory = await readValidatedRetirementInventoryWhileLocked(target, currentVersion, {
730
+ strictRetentionState: true,
731
+ allowedRetentionIntentGeneration: options.allowedRetentionIntentGeneration,
732
+ allowedRetentionTemporaryName: options.allowedRetentionTemporaryName,
733
+ allowedPruneProgressGeneration: options.allowedPruneProgressGeneration,
734
+ allowedPruneProgressTemporaryName: options.allowedPruneProgressTemporaryName
735
+ });
736
+ const head = inventory.records.filter((record) => sameUpdateTreeIdentity(record.owner.newTreeIdentity, inventory.actualIdentity));
737
+ if (head.length === 1) {
738
+ const current = head[0].owner;
739
+ if (current.newVersion !== inventory.actualVersion || !await matchesInstalledTree(target, current)) throw new Error("An installed update retirement record requires recovery");
740
+ }
741
+ const byInstalledIdentity = /* @__PURE__ */ new Map();
742
+ for (const { owner } of inventory.records) {
743
+ const key = retentionIdentityKey(owner.newTreeIdentity);
744
+ if (!key) throw new Error("An update retirement lineage requires recovery");
745
+ if (!byInstalledIdentity.has(key)) byInstalledIdentity.set(key, owner);
746
+ }
747
+ for (const { owner } of inventory.records) {
748
+ const previousKey = retentionIdentityKey(owner.previousTreeIdentity);
749
+ if (!previousKey) throw new Error("An update retirement lineage requires recovery");
750
+ const parent = byInstalledIdentity.get(previousKey);
751
+ if (parent && owner.previousVersion !== parent.newVersion) throw new Error("An update retirement lineage requires recovery");
752
+ }
753
+ return {
754
+ inventory,
755
+ plan: planUpdateRetention(inventory.actualIdentity, inventory.records.map(({ owner, healthy }) => ({
756
+ generation: owner.generation,
757
+ installed: owner.newTreeIdentity,
758
+ previous: owner.previousTreeIdentity,
759
+ healthy: options.allowUnhealthyReads === true || healthy
760
+ })))
761
+ };
762
+ }
763
+ /**
764
+ * Acquire shared leases on every validated retained generation. Keep the
765
+ * returned leases until all readers and response bodies have finished. A future
766
+ * deletion implementation must hold the update lock and the same generation's
767
+ * exclusive lease while it revalidates and removes that generation.
768
+ */
769
+ async function acquireRetainedUpdateTrees(options) {
770
+ const { target, currentVersion } = options;
771
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || target.includes("\0")) throw new Error("Invalid retained update tree lookup");
772
+ let retained;
773
+ try {
774
+ return await withUpdateLock(target, async () => {
775
+ retained = await acquireRetainedUpdateTreesWhileLocked(options);
776
+ return retained;
777
+ });
778
+ } catch (error) {
779
+ if (retained?.status === "acquired") try {
780
+ await retained.release();
781
+ } catch (releaseError) {
782
+ throw new AggregateError([error, releaseError], "Update lock release failed after retained tree acquisition", { cause: releaseError });
783
+ }
784
+ throw error;
785
+ }
786
+ }
787
+ /**
788
+ * Acquire retained generations while the caller holds the per-install update
789
+ * lock. A staged candidate is accepted only after its caller has run trusted
790
+ * resume validation; this function repeats the stage identity and descriptor
791
+ * checks before permitting the retention inventory.
792
+ */
793
+ async function acquireRetainedUpdateTreesWhileLocked(options) {
794
+ const { target, currentVersion } = options;
795
+ const stagedExists = await pathInfo(updateStagingFor(target));
796
+ if (stagedExists && (!options.validatedStagedVersion || !options.stagedTrust)) throw new Error("An update staging directory requires recovery");
797
+ let helperLiveness;
798
+ if (stagedExists) {
799
+ helperLiveness = await tryAcquireUpdateHelperLiveness(target);
800
+ if (!helperLiveness) return { status: "busy" };
801
+ }
802
+ const held = [];
803
+ const releaseHeld = async () => {
804
+ const failures = [];
805
+ for (const lease of held.splice(0).toReversed()) try {
806
+ await lease.release();
807
+ } catch (error) {
808
+ failures.push(error);
809
+ }
810
+ if (failures.length) throw new AggregateError(failures, "Could not release retained tree leases");
811
+ };
812
+ try {
813
+ const result = await (async () => {
814
+ const { inventory, plan: lineage } = await planRetentionWhileLocked(target, currentVersion, {
815
+ allowUnhealthyReads: true,
816
+ ...options.validatedStagedVersion === void 0 ? {} : {
817
+ validatedStagedVersion: options.validatedStagedVersion,
818
+ stagedTrust: options.stagedTrust
819
+ }
820
+ });
821
+ if (lineage.status !== "ready") throw new Error("Update retention lineage requires recovery");
822
+ if (!inventory.records.length) return { status: "none" };
823
+ const trees = [];
824
+ const ordered = inventory.records.toSorted((left, right) => {
825
+ const a = left.owner.generation.toLowerCase();
826
+ const b = right.owner.generation.toLowerCase();
827
+ return a < b ? -1 : a > b ? 1 : 0;
828
+ });
829
+ for (const { owner, paths } of ordered) {
830
+ const lease = await tryAcquireUpdateGenerationLease(target, owner.generation, "shared");
831
+ if (!lease) return { status: "busy" };
832
+ held.push(lease);
833
+ if (!await matchesOwnedTree(paths.tree, owner)) throw new Error("A retained update tree changed during lease acquisition");
834
+ trees.push(Object.freeze({
835
+ generation: owner.generation,
836
+ version: owner.previousVersion,
837
+ tree: paths.tree
838
+ }));
839
+ }
840
+ return {
841
+ status: "acquired",
842
+ trees: Object.freeze(trees)
843
+ };
844
+ })();
845
+ if (result.status !== "acquired") {
846
+ await releaseHeld();
847
+ return result;
848
+ }
849
+ let release;
850
+ const retained = Object.freeze({
851
+ ...result,
852
+ release: () => release ??= releaseHeld()
853
+ });
854
+ if (helperLiveness) {
855
+ const helper = helperLiveness;
856
+ helperLiveness = void 0;
857
+ try {
858
+ await helper.release();
859
+ } catch (error) {
860
+ try {
861
+ await releaseHeld();
862
+ } catch (releaseError) {
863
+ throw new AggregateError([error, releaseError], "Retained tree and helper leases failed to release", { cause: releaseError });
864
+ }
865
+ throw error;
866
+ }
867
+ }
868
+ return retained;
869
+ } catch (error) {
870
+ try {
871
+ await releaseHeld();
872
+ } catch (releaseError) {
873
+ throw new AggregateError([error, releaseError], "Retained tree acquisition and release failed", { cause: releaseError });
874
+ }
875
+ throw error;
876
+ } finally {
877
+ await helperLiveness?.release();
878
+ }
879
+ }
880
+ function isRetentionArtifactName(name, target) {
881
+ const foldedName = name.toLowerCase();
882
+ const baseName = basename(target).toLowerCase();
883
+ return foldedName.startsWith(`.${baseName}.framework-prune-`) || foldedName.startsWith(`..${baseName}.framework-prune-`);
884
+ }
885
+ /** Accept only one UUID-named publisher temporary for this exact marker. */
886
+ function retentionTemporaryName(names, target, generation) {
887
+ const markerName = basename(updateRetentionIntentPath(target, generation));
888
+ const temporaryPrefix = `.${markerName}.`;
889
+ const artifacts = names.filter((name) => isRetentionArtifactName(name, target));
890
+ const temporaryPrefixForTarget = `..${basename(target)}.framework-prune-`.toLowerCase();
891
+ const temporaryNames = artifacts.filter((name) => name.toLowerCase().startsWith(temporaryPrefixForTarget));
892
+ if (temporaryNames.length > 1) throw new Error("Multiple update retention temporaries require recovery");
893
+ let selected;
894
+ if (temporaryNames.length === 1) {
895
+ const name = temporaryNames[0];
896
+ const id = name.startsWith(temporaryPrefix) && name.endsWith(".tmp") ? name.slice(temporaryPrefix.length, -4) : "";
897
+ if (!PUBLISHER_TEMP_UUID.test(id)) throw new Error("Malformed update retention temporary requires recovery");
898
+ selected = name;
899
+ }
900
+ for (const name of artifacts) {
901
+ if (name === markerName || name === selected) continue;
902
+ throw new Error("An unrelated update retention artifact requires recovery");
903
+ }
904
+ return selected;
905
+ }
906
+ async function assertIntentMatchesRetentionPlan(target, inventory, plan, intent) {
907
+ if (plan.status !== "ready") throw new Error("Update retention intent requires recovery");
908
+ const selected = inventory.records.find(({ owner }) => owner.generation.toLowerCase() === intent.generation);
909
+ const installed = inventory.records.find(({ owner }) => owner.generation.toLowerCase() === plan.keep?.toLowerCase());
910
+ if (!selected || !installed || plan.prune[0]?.toLowerCase() !== intent.generation || !sameUpdateTreeIdentity(intent.previousTreeIdentity, selected.owner.previousTreeIdentity) || intent.installedGeneration !== installed.owner.generation.toLowerCase() || !sameUpdateTreeIdentity(intent.installedTreeIdentity, inventory.actualIdentity) || !sameUpdateTreeIdentity(intent.installedTreeIdentity, installed.owner.newTreeIdentity) || !await matchesInstalledTree(target, installed.owner)) throw new Error("Update retention intent is stale");
911
+ }
912
+ /**
913
+ * Inspect one published retention intent against the current install while
914
+ * holding the update lock. This validates recovery data only; it never changes
915
+ * the filesystem or grants deletion authority.
916
+ */
917
+ async function inspectUpdateRetentionCleanup(options) {
918
+ const { target, currentVersion, generation } = options;
919
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
920
+ updateRetentionIntentPath(target, generation);
921
+ return withUpdateLock(target, () => inspectRetentionWhileLocked(target, currentVersion, generation));
922
+ }
923
+ async function inspectRetentionWhileLocked(target, currentVersion, generation) {
924
+ const { inventory, plan } = await planRetentionWhileLocked(target, currentVersion, { allowedRetentionIntentGeneration: generation });
925
+ const intent = await readUpdateRetentionIntent(target, generation);
926
+ if (!intent) {
927
+ if (inventory.allowedIntentObserved) throw new Error("Update retention intent disappeared during inspection");
928
+ return null;
929
+ }
930
+ await assertIntentMatchesRetentionPlan(target, inventory, plan, intent);
931
+ return intent;
932
+ }
933
+ /**
934
+ * Request synchronization of a freshly validated marker under the update lock.
935
+ * This does not establish hardware-level durability or authorize deletion.
936
+ */
937
+ async function syncValidatedUpdateRetentionCleanup(options) {
938
+ const { target, currentVersion, generation } = options;
939
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
940
+ updateRetentionIntentPath(target, generation);
941
+ return withUpdateLock(target, async () => {
942
+ const intent = await inspectRetentionWhileLocked(target, currentVersion, generation);
943
+ if (!intent) throw new Error("Update retention intent is missing");
944
+ const identity = await syncUpdateRetentionIntent(intent);
945
+ const verified = await inspectRetentionWhileLocked(target, currentVersion, generation);
946
+ const finalMarker = await readUpdateRetentionIntentFile(updateRetentionIntentPath(target, generation), target, generation);
947
+ if (!verified || !sameRetentionIntent(intent, verified) || !finalMarker || !sameRetentionIntent(intent, finalMarker.intent) || !sameUpdateTreeIdentity(identity, finalMarker.identity)) throw new Error("Update retention intent changed during synchronization");
948
+ return identity;
949
+ });
950
+ }
951
+ /**
952
+ * Promote one publisher temporary left by an interrupted intent publication.
953
+ * Under the update lock this requires exactly one canonical temporary, no
954
+ * final marker, and no other retention artifacts, then validates the bounded
955
+ * file and oldest eligible cleanup plan twice before a no-replace hard link.
956
+ * It leaves both names in place for reconcileUpdateRetentionCleanup. If the
957
+ * link call fails, whether a final name was created is treated as unknown; if
958
+ * post-link validation fails, the link is known to exist. Both failures
959
+ * preserve every path for inspection. This operation makes no power-loss
960
+ * durability claim and never removes a retirement tree or marker.
961
+ */
962
+ async function promoteOrphanUpdateRetentionCleanup(options) {
963
+ const { target, currentVersion, generation } = options;
964
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
965
+ const finalPath = updateRetentionIntentPath(target, generation);
966
+ const readOrphan = async (expectedTemporaryName) => {
967
+ const names = await readdir(dirname(target));
968
+ const temporaryName = retentionTemporaryName(names, target, generation);
969
+ if (!temporaryName) throw new Error("Update retention orphan temporary is missing");
970
+ if (expectedTemporaryName !== void 0 && temporaryName !== expectedTemporaryName) throw new Error("Update retention orphan temporary changed");
971
+ if (names.includes(basename(finalPath))) throw new Error("Update retention final intent already exists");
972
+ const temporaryPath = join(dirname(finalPath), temporaryName);
973
+ const { inventory, plan } = await planRetentionWhileLocked(target, currentVersion, {
974
+ allowedRetentionIntentGeneration: generation,
975
+ allowedRetentionTemporaryName: temporaryName
976
+ });
977
+ if (inventory.allowedIntentObserved) throw new Error("Update retention final intent appeared during promotion");
978
+ const temporaryFile = await readUpdateRetentionIntentFile(temporaryPath, target, generation);
979
+ if (!temporaryFile) throw new Error("Update retention orphan temporary disappeared during promotion");
980
+ await assertIntentMatchesRetentionPlan(target, inventory, plan, temporaryFile.intent);
981
+ return {
982
+ temporaryName,
983
+ temporaryPath,
984
+ temporaryFile
985
+ };
986
+ };
987
+ return withUpdateLock(target, async () => {
988
+ const initial = await readOrphan();
989
+ const beforeLink = await readOrphan(initial.temporaryName);
990
+ if (!sameRetentionIntent(beforeLink.temporaryFile.intent, initial.temporaryFile.intent) || !sameUpdateTreeIdentity(beforeLink.temporaryFile.identity, initial.temporaryFile.identity)) throw new Error("Update retention orphan changed before promotion");
991
+ try {
992
+ await link(beforeLink.temporaryPath, finalPath);
993
+ } catch (cause) {
994
+ throw new UpdateRetentionOrphanPromotionError(beforeLink.temporaryPath, finalPath, "unknown", cause);
995
+ }
996
+ try {
997
+ const temporaryName = retentionTemporaryName(await readdir(dirname(target)), target, generation);
998
+ if (temporaryName !== beforeLink.temporaryName) throw new Error("Update retention orphan temporary changed after promotion");
999
+ const { inventory, plan } = await planRetentionWhileLocked(target, currentVersion, {
1000
+ allowedRetentionIntentGeneration: generation,
1001
+ allowedRetentionTemporaryName: temporaryName
1002
+ });
1003
+ if (!inventory.allowedIntentObserved) throw new Error("Update retention final intent is missing after promotion");
1004
+ const finalFile = await readUpdateRetentionIntentFile(finalPath, target, generation);
1005
+ const temporaryFile = await readUpdateRetentionIntentFile(beforeLink.temporaryPath, target, generation);
1006
+ if (!finalFile || !temporaryFile) throw new Error("Update retention file disappeared after promotion");
1007
+ await assertIntentMatchesRetentionPlan(target, inventory, plan, finalFile.intent);
1008
+ if (!sameRetentionIntent(finalFile.intent, beforeLink.temporaryFile.intent) || !sameRetentionIntent(temporaryFile.intent, beforeLink.temporaryFile.intent) || !sameUpdateTreeIdentity(finalFile.identity, beforeLink.temporaryFile.identity) || !sameUpdateTreeIdentity(temporaryFile.identity, beforeLink.temporaryFile.identity)) throw new Error("Update retention files changed after promotion");
1009
+ return {
1010
+ status: "promoted",
1011
+ intent: finalFile.intent,
1012
+ temporaryPath: beforeLink.temporaryPath,
1013
+ finalPath
1014
+ };
1015
+ } catch (cause) {
1016
+ throw new UpdateRetentionOrphanPromotionError(beforeLink.temporaryPath, finalPath, "linked", cause);
1017
+ }
1018
+ });
1019
+ }
1020
+ /**
1021
+ * Reconcile only the publisher's extra hard link after validating the final
1022
+ * intent against a fresh retention plan under the update lock. This never
1023
+ * deletes a final marker, retirement tree, claim, or receipt, and makes no
1024
+ * power-loss durability claim.
1025
+ */
1026
+ async function reconcileUpdateRetentionCleanup(options) {
1027
+ const { target, currentVersion, generation } = options;
1028
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
1029
+ const markerPath = updateRetentionIntentPath(target, generation);
1030
+ return withUpdateLock(target, async () => {
1031
+ const temporaryName = retentionTemporaryName(await readdir(dirname(target)), target, generation);
1032
+ const { inventory, plan } = await planRetentionWhileLocked(target, currentVersion, {
1033
+ allowedRetentionIntentGeneration: generation,
1034
+ ...temporaryName ? { allowedRetentionTemporaryName: temporaryName } : {}
1035
+ });
1036
+ if (!inventory.allowedIntentObserved) throw new Error("Update retention intent is missing or changed during reconciliation");
1037
+ const markerFile = await readUpdateRetentionIntentFile(markerPath, target, generation);
1038
+ if (!markerFile) throw new Error("Update retention intent is missing");
1039
+ await assertIntentMatchesRetentionPlan(target, inventory, plan, markerFile.intent);
1040
+ if (!temporaryName) return {
1041
+ status: "already-clean",
1042
+ intent: markerFile.intent
1043
+ };
1044
+ const temporaryPath = join(dirname(markerPath), temporaryName);
1045
+ const temporaryFile = await readUpdateRetentionIntentFile(temporaryPath, target, generation);
1046
+ if (!temporaryFile) throw new Error("Update retention temporary disappeared during reconciliation");
1047
+ if (!sameRetentionIntent(temporaryFile.intent, markerFile.intent) || !sameUpdateTreeIdentity(temporaryFile.identity, markerFile.identity)) throw new Error("Update retention temporary does not match the final intent");
1048
+ const before = await planRetentionWhileLocked(target, currentVersion, {
1049
+ allowedRetentionIntentGeneration: generation,
1050
+ allowedRetentionTemporaryName: temporaryName
1051
+ });
1052
+ if (!before.inventory.allowedIntentObserved) throw new Error("Update retention intent disappeared before reconciliation");
1053
+ const markerBefore = await readUpdateRetentionIntentFile(markerPath, target, generation);
1054
+ const temporaryBefore = await readUpdateRetentionIntentFile(temporaryPath, target, generation);
1055
+ if (!markerBefore || !temporaryBefore) throw new Error("Update retention file disappeared before reconciliation");
1056
+ await assertIntentMatchesRetentionPlan(target, before.inventory, before.plan, markerBefore.intent);
1057
+ if (!sameRetentionIntent(markerBefore.intent, markerFile.intent) || !sameRetentionIntent(temporaryBefore.intent, markerFile.intent) || !sameUpdateTreeIdentity(markerBefore.identity, markerFile.identity) || !sameUpdateTreeIdentity(temporaryBefore.identity, markerFile.identity)) throw new Error("Update retention files changed before reconciliation");
1058
+ await unlink(temporaryPath);
1059
+ const after = await planRetentionWhileLocked(target, currentVersion, { allowedRetentionIntentGeneration: generation });
1060
+ if (!after.inventory.allowedIntentObserved) throw new Error("Update retention intent disappeared after reconciliation");
1061
+ const markerAfter = await readUpdateRetentionIntentFile(markerPath, target, generation);
1062
+ if (!markerAfter) throw new Error("Update retention intent disappeared after reconciliation");
1063
+ await assertIntentMatchesRetentionPlan(target, after.inventory, after.plan, markerAfter.intent);
1064
+ if (!sameRetentionIntent(markerAfter.intent, markerFile.intent) || !sameUpdateTreeIdentity(markerAfter.identity, markerFile.identity)) throw new Error("Update retention intent changed after reconciliation");
1065
+ if (await pathInfo(temporaryPath)) throw new Error("Update retention temporary remains after reconciliation");
1066
+ return {
1067
+ status: "temporary-removed",
1068
+ intent: markerAfter.intent,
1069
+ temporaryPath
1070
+ };
1071
+ });
1072
+ }
1073
+ /**
1074
+ * Record the oldest eligible cleanup candidate while holding the update lock.
1075
+ * This WIP operation does not delete data or grant authority to a later caller.
1076
+ * Intent publication is not yet power-loss durable.
1077
+ */
1078
+ async function beginUpdateRetentionCleanup(options) {
1079
+ const { target, currentVersion } = options;
1080
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update retention lookup");
1081
+ return withUpdateLock(target, async () => {
1082
+ const { inventory, plan } = await planRetentionWhileLocked(target, currentVersion);
1083
+ if (plan.status !== "ready") throw new Error("Update retention lineage requires recovery");
1084
+ const candidate = plan.prune[0];
1085
+ if (!candidate) return null;
1086
+ const selected = inventory.records.find(({ owner }) => owner.generation === candidate);
1087
+ const installed = inventory.records.find(({ owner }) => owner.generation === plan.keep);
1088
+ if (!selected || !installed) throw new Error("Update retention lineage changed");
1089
+ const intent = {
1090
+ schema: 1,
1091
+ phase: "prune-previous-tree",
1092
+ target,
1093
+ generation: selected.owner.generation.toLowerCase(),
1094
+ previousTreeIdentity: selected.owner.previousTreeIdentity,
1095
+ installedGeneration: installed.owner.generation.toLowerCase(),
1096
+ installedTreeIdentity: inventory.actualIdentity
1097
+ };
1098
+ return {
1099
+ intent,
1100
+ publication: await publishUpdateRetentionIntent(intent)
1101
+ };
1102
+ });
1103
+ }
1104
+ /**
1105
+ * Make one explicit, bounded prune step for an already-published retention
1106
+ * intent. Ordinary inventory readers fail closed while this progress record
1107
+ * exists. Calls serialize under the install lock, then take the generation's
1108
+ * exclusive lease before inspecting or changing its retired tree.
1109
+ *
1110
+ * This currently supports only the tested macOS ARM64 directory-relative
1111
+ * remover. It requests file and directory synchronization before destructive
1112
+ * transitions, but those calls do not prove hardware persistence or recovery
1113
+ * after power loss. Callers must invoke this explicitly; startup and updater
1114
+ * flows do not prune automatically.
1115
+ */
1116
+ async function pruneUpdateRetentionStep(options) {
1117
+ const { target, currentVersion, generation } = options;
1118
+ const maxOperations = options.maxOperations ?? 64;
1119
+ if (typeof currentVersion !== "string" || !VERSION.test(currentVersion) || typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || !Number.isSafeInteger(maxOperations) || maxOperations < 1 || maxOperations > 4096) throw new Error("Invalid update retention prune request");
1120
+ updateRetirementPaths(target, generation);
1121
+ if (process.platform !== "darwin" || process.arch !== "arm64") return { status: "recovery-required" };
1122
+ return withUpdateLock(target, async () => {
1123
+ const diskIntent = await readUpdateRetentionIntent(target, generation);
1124
+ const progress = await readPruneProgress(target, generation, diskIntent);
1125
+ const progressTemporaryName = await findPruneProgressTemporaryName(target, generation);
1126
+ const intent = diskIntent ?? progress?.intent;
1127
+ if (!intent && !progress && !progressTemporaryName) {
1128
+ if ((await planRetentionWhileLocked(target, currentVersion)).plan.status === "ready") return { status: "none" };
1129
+ return { status: "recovery-required" };
1130
+ }
1131
+ if (!intent || intent.generation !== generation.toLowerCase()) return { status: "recovery-required" };
1132
+ let context = await planRetentionWhileLocked(target, currentVersion, {
1133
+ allowedRetentionIntentGeneration: generation,
1134
+ ...progress || progressTemporaryName ? { allowedPruneProgressGeneration: generation } : {},
1135
+ ...progressTemporaryName ? { allowedPruneProgressTemporaryName: progressTemporaryName } : {}
1136
+ });
1137
+ if (context.plan.status !== "ready") return { status: "recovery-required" };
1138
+ await assertIntentMatchesRetentionPlan(target, context.inventory, context.plan, intent);
1139
+ if (context.plan.prune[0]?.toLowerCase() !== generation.toLowerCase()) return { status: "recovery-required" };
1140
+ let selected = context.inventory.records.find(({ owner }) => owner.generation.toLowerCase() === generation.toLowerCase());
1141
+ if (!selected) return { status: "recovery-required" };
1142
+ const lease = await tryAcquireUpdateGenerationLease(target, generation, "exclusive");
1143
+ if (!lease) return { status: "busy" };
1144
+ try {
1145
+ const currentIntent = await readUpdateRetentionIntent(target, generation);
1146
+ let currentProgress = await readPruneProgress(target, generation, currentIntent);
1147
+ let currentProgressTemporaryName = await findPruneProgressTemporaryName(target, generation);
1148
+ if (currentIntent && !sameRetentionIntent(currentIntent, intent) || currentProgress && (!sameRetentionIntent(currentProgress.intent, intent) || !ownerMatches(currentProgress.owner, selected.owner)) || progress && !currentProgress || !progress && currentProgress || currentProgressTemporaryName !== progressTemporaryName) return { status: "recovery-required" };
1149
+ context = await planRetentionWhileLocked(target, currentVersion, {
1150
+ allowedRetentionIntentGeneration: generation,
1151
+ ...currentProgress || currentProgressTemporaryName ? { allowedPruneProgressGeneration: generation } : {},
1152
+ ...currentProgressTemporaryName ? { allowedPruneProgressTemporaryName: currentProgressTemporaryName } : {}
1153
+ });
1154
+ if (context.plan.status !== "ready") return { status: "recovery-required" };
1155
+ await assertIntentMatchesRetentionPlan(target, context.inventory, context.plan, intent);
1156
+ if (context.plan.prune[0]?.toLowerCase() !== generation.toLowerCase()) return { status: "recovery-required" };
1157
+ selected = context.inventory.records.find(({ owner }) => owner.generation.toLowerCase() === generation.toLowerCase());
1158
+ if (!selected) return { status: "recovery-required" };
1159
+ if (currentIntent) await syncUpdateRetentionIntent(currentIntent);
1160
+ if (currentProgressTemporaryName) {
1161
+ const temporaryPath = join(dirname(target), currentProgressTemporaryName);
1162
+ const temporary = await readPruneProgressFile(temporaryPath, target, generation, currentIntent, selected.owner);
1163
+ if (!temporary) return { status: "recovery-required" };
1164
+ if (currentProgress) {
1165
+ if (!healthReceiptMatches(temporary.healthReceipt, currentProgress.healthReceipt)) return { status: "recovery-required" };
1166
+ await unlink(temporaryPath);
1167
+ if (await pathInfo(temporaryPath)) return { status: "recovery-required" };
1168
+ await syncPruneDirectory(dirname(temporaryPath), intent.previousTreeIdentity.device);
1169
+ } else {
1170
+ if (temporary.phase !== "deleting" || !currentIntent) return { status: "recovery-required" };
1171
+ const finalPath = retentionPruneProgressPath(target, generation);
1172
+ if (await pathInfo(finalPath)) return { status: "recovery-required" };
1173
+ await syncPruneFile(temporaryPath, intent.previousTreeIdentity.device);
1174
+ await link(temporaryPath, finalPath);
1175
+ await syncPruneDirectory(dirname(finalPath), intent.previousTreeIdentity.device);
1176
+ currentProgress = await readPruneProgress(target, generation, currentIntent);
1177
+ if (!currentProgress || !ownerMatches(currentProgress.owner, temporary.owner) || !healthReceiptMatches(currentProgress.healthReceipt, temporary.healthReceipt)) return { status: "recovery-required" };
1178
+ await unlink(temporaryPath);
1179
+ if (await pathInfo(temporaryPath)) return { status: "recovery-required" };
1180
+ await syncPruneDirectory(dirname(temporaryPath), intent.previousTreeIdentity.device);
1181
+ }
1182
+ context = await planRetentionWhileLocked(target, currentVersion, {
1183
+ allowedRetentionIntentGeneration: generation,
1184
+ allowedPruneProgressGeneration: generation
1185
+ });
1186
+ if (context.plan.status !== "ready") return { status: "recovery-required" };
1187
+ await assertIntentMatchesRetentionPlan(target, context.inventory, context.plan, intent);
1188
+ if (context.plan.prune[0]?.toLowerCase() !== generation.toLowerCase()) return { status: "recovery-required" };
1189
+ selected = context.inventory.records.find(({ owner }) => owner.generation.toLowerCase() === generation.toLowerCase());
1190
+ if (!selected) return { status: "recovery-required" };
1191
+ }
1192
+ if (!currentProgress || currentProgress.phase === "deleting") await syncPruneRecoveryEvidence(target, intent, context.inventory);
1193
+ if (currentProgress) await syncPruneProgress(target, generation, currentProgress);
1194
+ const progressHealthReceipt = currentProgress?.healthReceipt ?? await readHealthReceipt(selected.paths.healthReceipt);
1195
+ if (!healthReceiptMatches(progressHealthReceipt, healthReceiptFor(selected.owner))) return { status: "recovery-required" };
1196
+ let prioritizeVersionMarker;
1197
+ if (!currentProgress || currentProgress.phase === "deleting") {
1198
+ const versionInfo = await pathInfo(join(selected.paths.tree, "Contents", "Resources", "version.json"));
1199
+ if (!currentProgress && (!versionInfo?.isFile() || versionInfo.isSymbolicLink())) return { status: "recovery-required" };
1200
+ if (versionInfo) {
1201
+ if (!versionInfo.isFile() || versionInfo.isSymbolicLink()) return { status: "recovery-required" };
1202
+ prioritizeVersionMarker = {
1203
+ path: [
1204
+ "Contents",
1205
+ "Resources",
1206
+ "version.json"
1207
+ ],
1208
+ version: selected.owner.previousVersion
1209
+ };
1210
+ }
1211
+ }
1212
+ if (!currentProgress) {
1213
+ if (!await publishPruneProgress(intent, selected.owner, progressHealthReceipt, "deleting")) return { status: "recovery-required" };
1214
+ const removed = await removeDirectoryContentsChunk({
1215
+ root: selected.paths.tree,
1216
+ expectedRootIdentity: intent.previousTreeIdentity,
1217
+ maxOperations,
1218
+ prioritizeVersionMarker
1219
+ });
1220
+ if (removed.status === "empty") {
1221
+ if (!await publishPruneProgress(intent, selected.owner, progressHealthReceipt, "empty")) return { status: "recovery-required" };
1222
+ }
1223
+ return {
1224
+ status: "more",
1225
+ removed: removed.removed
1226
+ };
1227
+ }
1228
+ if (currentProgress.phase === "deleting") {
1229
+ const removed = await removeDirectoryContentsChunk({
1230
+ root: selected.paths.tree,
1231
+ expectedRootIdentity: intent.previousTreeIdentity,
1232
+ maxOperations,
1233
+ prioritizeVersionMarker
1234
+ });
1235
+ if (removed.status === "empty") {
1236
+ if (!await publishPruneProgress(intent, selected.owner, progressHealthReceipt, "empty")) return { status: "recovery-required" };
1237
+ }
1238
+ return {
1239
+ status: "more",
1240
+ removed: removed.removed
1241
+ };
1242
+ }
1243
+ const treeInfo = await pathInfo(selected.paths.tree);
1244
+ if (treeInfo) {
1245
+ if (!treeInfo.isDirectory() || treeInfo.isSymbolicLink() || !await samePathTreeIdentity(selected.paths.tree, intent.previousTreeIdentity) || (await readdir(selected.paths.tree)).length !== 0) return { status: "recovery-required" };
1246
+ await rmdir(selected.paths.tree);
1247
+ }
1248
+ if (await pathInfo(selected.paths.container)) {
1249
+ if (await pathInfo(selected.paths.healthReceipt)) {
1250
+ const receipt = await readHealthReceipt(selected.paths.healthReceipt);
1251
+ if (!receipt || !healthReceiptMatches(receipt, healthReceiptFor(selected.owner))) return { status: "recovery-required" };
1252
+ await unlink(selected.paths.healthReceipt);
1253
+ }
1254
+ if (await pathInfo(selected.paths.claim)) {
1255
+ const currentOwner = await readOwner(selected.paths.claim);
1256
+ if (!currentOwner || !ownerMatches(currentOwner, selected.owner)) return { status: "recovery-required" };
1257
+ await unlink(selected.paths.claim);
1258
+ }
1259
+ const currentDiskIntent = await readUpdateRetentionIntent(target, generation);
1260
+ if (currentDiskIntent) {
1261
+ if (!sameRetentionIntent(currentDiskIntent, intent)) return { status: "recovery-required" };
1262
+ await unlink(updateRetentionIntentPath(target, generation));
1263
+ }
1264
+ if ((await readdir(selected.paths.container)).length !== 0) return { status: "recovery-required" };
1265
+ await syncPruneDirectory(selected.paths.container, intent.previousTreeIdentity.device);
1266
+ await rmdir(selected.paths.container);
1267
+ } else {
1268
+ if (await pathInfo(selected.paths.claim)) {
1269
+ const currentOwner = await readOwner(selected.paths.claim);
1270
+ if (!currentOwner || !ownerMatches(currentOwner, selected.owner)) return { status: "recovery-required" };
1271
+ await unlink(selected.paths.claim);
1272
+ }
1273
+ const currentDiskIntent = await readUpdateRetentionIntent(target, generation);
1274
+ if (currentDiskIntent) {
1275
+ if (!sameRetentionIntent(currentDiskIntent, intent)) return { status: "recovery-required" };
1276
+ await unlink(updateRetentionIntentPath(target, generation));
1277
+ }
1278
+ }
1279
+ await syncPruneDirectory(dirname(target), intent.previousTreeIdentity.device);
1280
+ const progressPath = retentionPruneProgressPath(target, generation);
1281
+ const finalProgress = await readPruneProgressFile(progressPath, target, generation, intent, selected.owner);
1282
+ if (!finalProgress || finalProgress.phase !== "empty") return { status: "recovery-required" };
1283
+ await unlink(progressPath);
1284
+ await syncPruneDirectory(dirname(target), intent.previousTreeIdentity.device);
1285
+ return { status: "pruned" };
1286
+ } finally {
1287
+ await lease.release();
1288
+ }
1289
+ });
1290
+ }
1291
+ async function acknowledgeUpdateHealthWhileLocked(target, token) {
1292
+ if (typeof token !== "object" || token === null || !UUID.test(token.generation) || typeof token.version !== "string" || !VERSION.test(token.version)) return false;
1293
+ const paths = updateRetirementPaths(target, token.generation);
1294
+ const claimInfo = await pathInfo(paths.claim);
1295
+ const owner = await readOwner(paths.claim);
1296
+ if (!claimInfo?.isFile() || claimInfo.isSymbolicLink() || !owner || owner.target !== target || owner.generation !== token.generation || owner.newVersion !== token.version || !await matchesInstalledTree(target, owner) || !await validRetirementContainer(owner, paths)) return false;
1297
+ const expected = healthReceiptFor(owner);
1298
+ if (await pathInfo(paths.healthReceipt)) return healthReceiptMatches(await readHealthReceipt(paths.healthReceipt), expected);
1299
+ const entries = await readdir(paths.container);
1300
+ for (const name of entries.filter(isMatchingHealthTemporary)) {
1301
+ const temporary = join(paths.container, name);
1302
+ const receipt = await readHealthReceipt(temporary);
1303
+ if (!receipt) continue;
1304
+ if (!healthReceiptMatches(receipt, expected)) return false;
1305
+ try {
1306
+ renameUpdateExclusive(temporary, paths.healthReceipt);
1307
+ } catch {
1308
+ return healthReceiptMatches(await readHealthReceipt(paths.healthReceipt), expected);
1309
+ }
1310
+ return healthReceiptMatches(await readHealthReceipt(paths.healthReceipt), expected) && await matchesInstalledTree(target, owner);
1311
+ }
1312
+ const temporary = join(paths.container, `${paths.healthTemporaryPrefix}${randomUUID()}.tmp`);
1313
+ try {
1314
+ await writeFile(temporary, JSON.stringify(expected) + "\n", {
1315
+ flag: "wx",
1316
+ mode: 384
1317
+ });
1318
+ if (!healthReceiptMatches(await readHealthReceipt(temporary), expected)) return false;
1319
+ renameUpdateExclusive(temporary, paths.healthReceipt);
1320
+ } catch {
1321
+ return healthReceiptMatches(await readHealthReceipt(paths.healthReceipt), expected);
1322
+ }
1323
+ return healthReceiptMatches(await readHealthReceipt(paths.healthReceipt), expected) && await matchesInstalledTree(target, owner) && await matchesOwnedTree(paths.tree, owner);
1324
+ }
1325
+ /** Explicitly acknowledge an exact installed generation after app-owned readiness checks. */
1326
+ async function acknowledgeRetiredUpdateHealthy(options) {
1327
+ if (!await withUpdateLock(options.target, () => acknowledgeUpdateHealthWhileLocked(options.target, options.acknowledgement))) throw new Error("The update health acknowledgement did not match the installed generation");
1328
+ }
1329
+ /** Reconcile the exact unlink/rmdir completion boundary while holding the install lock. */
1330
+ async function reconcileRetirementCleanupMarkerWhileLocked(options) {
1331
+ const { target, staging, currentVersion } = options;
1332
+ const markerPath = join(dirname(target), `.${basename(target)}.framework-update-cleanup.json`);
1333
+ if (!await pathInfo(markerPath)) return "none";
1334
+ const marker = await readCleanupMarker(markerPath);
1335
+ if (!marker || marker.target !== target || marker.version !== currentVersion) return "recovery-required";
1336
+ const targetInfo = await pathInfo(target);
1337
+ if (!targetInfo?.isDirectory() || targetInfo.isSymbolicLink() || await readUpdateTreeVersion(target) !== marker.version) return "recovery-required";
1338
+ const paths = updateRetirementPaths(target, marker.generation);
1339
+ const owner = await readOwner(paths.claim);
1340
+ if (!owner || owner.target !== target || owner.generation !== marker.generation || owner.newVersion !== marker.version || marker.claim !== basename(paths.claim) || !await matchesOwnedTree(paths.tree, owner)) return "recovery-required";
1341
+ const containerInfo = await pathInfo(paths.container);
1342
+ if (!containerInfo?.isDirectory() || containerInfo.isSymbolicLink()) return "recovery-required";
1343
+ const containerEntries = await readdir(paths.container);
1344
+ if (containerEntries.length !== 1 || containerEntries[0] !== "tree") return "recovery-required";
1345
+ const stagingInfo = await pathInfo(staging);
1346
+ if (stagingInfo) {
1347
+ if (!stagingInfo.isDirectory() || stagingInfo.isSymbolicLink()) return "recovery-required";
1348
+ if ((await readdir(staging)).length !== 0) return "recovery-required";
1349
+ await rmdir(staging);
1350
+ }
1351
+ if (!cleanupMarkerMatches(await readCleanupMarker(markerPath), marker)) return "recovery-required";
1352
+ await unlink(markerPath);
1353
+ return "updated";
1354
+ }
1355
+ async function knownStagingEntriesOnly(staging, generation) {
1356
+ const known = /* @__PURE__ */ new Set([
1357
+ "candidate",
1358
+ "helper",
1359
+ "helper-armed",
1360
+ "helper-ready",
1361
+ "cancel.json",
1362
+ "cancel-ack.json",
1363
+ "request.json",
1364
+ "state.json"
1365
+ ]);
1366
+ const stateTemporary = new RegExp(`^\\.state-${generation}-[0-9a-f-]{36}\\.tmp$`, "i");
1367
+ return (await readdir(staging)).every((name) => known.has(name) || stateTemporary.test(name));
1368
+ }
1369
+ async function removeKnownStateTemporaries(staging, generation) {
1370
+ const stateTemporary = new RegExp(`^\\.state-${generation}-[0-9a-f-]{36}\\.tmp$`, "i");
1371
+ for (const name of await readdir(staging)) {
1372
+ if (!stateTemporary.test(name)) continue;
1373
+ const path = join(staging, name);
1374
+ const info = await pathInfo(path);
1375
+ if (!info || !info.isFile() || info.isSymbolicLink()) return false;
1376
+ await unlink(path);
1377
+ }
1378
+ return true;
1379
+ }
1380
+ async function cleanupRetiredStaging(target, staging, state) {
1381
+ if (!await knownStagingEntriesOnly(staging, state.generation)) return false;
1382
+ if (await pathInfo(join(staging, "candidate"))) return false;
1383
+ await rm(join(staging, "request.json"), { force: true });
1384
+ await rm(join(staging, "helper-armed"), { force: true });
1385
+ await rm(join(staging, "helper-ready"), { force: true });
1386
+ await rm(join(staging, "cancel.json"), { force: true });
1387
+ await rm(join(staging, "cancel-ack.json"), { force: true });
1388
+ await rm(join(staging, "helper"), {
1389
+ recursive: true,
1390
+ force: true
1391
+ });
1392
+ if (!await removeKnownStateTemporaries(staging, state.generation)) return false;
1393
+ const current = await readUpdateStageState(staging);
1394
+ if (!current || current.generation !== state.generation || current.phase !== "retired") return false;
1395
+ const entries = await readdir(staging);
1396
+ if (entries.length !== 1 || entries[0] !== "state.json") return false;
1397
+ if (!await ensureCleanupMarker(target, state)) return false;
1398
+ await unlink(join(staging, "state.json"));
1399
+ await rmdir(staging);
1400
+ return await reconcileRetirementCleanupMarkerWhileLocked({
1401
+ target,
1402
+ staging,
1403
+ currentVersion: state.version
1404
+ }) === "updated";
1405
+ }
1406
+ /**
1407
+ * Reconcile a completed exchange while the stable per-install lock is held.
1408
+ * The old app tree is moved without replacement into a UUID-owned container;
1409
+ * it is never modified or deleted here. Atomic rename publication protects
1410
+ * against process crashes, but this protocol makes no power-loss claim.
1411
+ * Health is recorded only after an explicit host call; app-owned readiness
1412
+ * criteria and quarantine retention/cleanup policy remain WIP.
1413
+ */
1414
+ async function retireCompletedUpdateWhileLocked(options) {
1415
+ const { target, staging } = options;
1416
+ let state = options.state;
1417
+ if (updateStagingFor(target) !== staging || ![
1418
+ "completed",
1419
+ "retiring",
1420
+ "retired"
1421
+ ].includes(state.phase) || state.phase !== "completed" && !state.previousTreeIdentity) return false;
1422
+ try {
1423
+ const targetInfo = await lstat(target);
1424
+ if (!targetInfo.isDirectory() || targetInfo.isSymbolicLink() || await readUpdateTreeVersion(target) !== state.version) return false;
1425
+ } catch {
1426
+ return false;
1427
+ }
1428
+ if (!state.candidateTreeIdentity || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(target), state.candidateTreeIdentity)) return false;
1429
+ const paths = updateRetirementPaths(target, state.generation);
1430
+ if (state.phase === "completed") {
1431
+ if (!await matchesOldTree(join(staging, "candidate"), state) || await pathInfo(paths.container) || await pathInfo(paths.claim)) return false;
1432
+ state = {
1433
+ ...state,
1434
+ phase: "retiring"
1435
+ };
1436
+ await writeUpdateStageState(staging, state);
1437
+ }
1438
+ if (state.phase === "retiring") {
1439
+ const candidate = join(staging, "candidate");
1440
+ const candidateInfo = await pathInfo(candidate);
1441
+ const containerInfo = await pathInfo(paths.container);
1442
+ const treeInfo = await pathInfo(paths.tree);
1443
+ if (candidateInfo && !await matchesOldTree(candidate, state)) return false;
1444
+ if (treeInfo && !await matchesOldTree(paths.tree, state)) return false;
1445
+ if (candidateInfo && treeInfo) return false;
1446
+ if (!candidateInfo && !treeInfo) return false;
1447
+ const claimInfo = await pathInfo(paths.claim);
1448
+ if (containerInfo && !claimInfo) return false;
1449
+ if (!containerInfo && candidateInfo && !claimInfo && !await ensureClaim(target, state)) return false;
1450
+ const expectedOwner = ownerFor(target, state);
1451
+ if (claimInfo && (!expectedOwner || !await ownerMatches(await readOwner(paths.claim), expectedOwner))) return false;
1452
+ if (!claimInfo && (!expectedOwner || !await ownerMatches(await readOwner(paths.claim), expectedOwner))) return false;
1453
+ if (!containerInfo) try {
1454
+ await mkdir(paths.container, { mode: 448 });
1455
+ } catch {
1456
+ return false;
1457
+ }
1458
+ const currentContainer = await pathInfo(paths.container);
1459
+ if (!currentContainer?.isDirectory() || currentContainer.isSymbolicLink()) return false;
1460
+ const entries = await readdir(paths.container);
1461
+ if (candidateInfo) {
1462
+ if (entries.length !== 0) return false;
1463
+ try {
1464
+ renameUpdateExclusive(candidate, paths.tree);
1465
+ } catch {
1466
+ return false;
1467
+ }
1468
+ } else if (entries.length !== 1 || entries[0] !== "tree") return false;
1469
+ if (!await matchesOldTree(paths.tree, state)) return false;
1470
+ state = {
1471
+ ...state,
1472
+ phase: "retired"
1473
+ };
1474
+ await writeUpdateStageState(staging, state);
1475
+ }
1476
+ if (state.phase !== "retired") return false;
1477
+ const owner = ownerFor(target, state);
1478
+ if (!owner || !await ownerMatches(await readOwner(paths.claim), owner) || !await matchesInstalledTree(target, owner) || await pathInfo(join(staging, "candidate")) || !await matchesOldTree(paths.tree, state)) return false;
1479
+ const finalContainer = await pathInfo(paths.container);
1480
+ if (!finalContainer?.isDirectory() || finalContainer.isSymbolicLink()) return false;
1481
+ const finalEntries = await readdir(paths.container);
1482
+ if (finalEntries.length !== 1 || finalEntries[0] !== "tree") return false;
1483
+ return cleanupRetiredStaging(target, staging, state);
1484
+ }
1485
+ export { UpdateRetentionOrphanPromotionError, acknowledgeRetiredUpdateHealthy, acquireRetainedUpdateTrees, acquireRetainedUpdateTreesWhileLocked, assertNoUpdateRetentionPruneArtifactsWhileLocked, beginUpdateRetentionCleanup, findPendingUpdateHealthAcknowledgement, inspectUpdateRetentionCleanup, planValidatedUpdateRetention, promoteOrphanUpdateRetentionCleanup, pruneUpdateRetentionStep, reconcileRetirementCleanupMarkerWhileLocked, reconcileUpdateRetentionCleanup, retireCompletedUpdateWhileLocked, syncValidatedUpdateRetentionCleanup, updateRetirementPaths };