@adea-ai/app-framework 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +177 -15
  2. package/dist/app/create-application.d.ts +2 -0
  3. package/dist/app/create-application.js +6 -0
  4. package/dist/app/service-registry.js +4 -0
  5. package/dist/appearance/custom-theme-import.js +43 -7
  6. package/dist/appearance/custom-theme-library.d.ts +2 -0
  7. package/dist/appearance/custom-theme-library.js +5 -1
  8. package/dist/appearance/theme-record-adapter.js +4 -2
  9. package/dist/appearance/theme-registry.js +7 -1
  10. package/dist/cli/cli-runner.d.ts +4 -0
  11. package/dist/cli/cli-runner.js +14 -1
  12. package/dist/cli/create-application-cli.js +4 -2
  13. package/dist/cli/release-cut-cli.js +2 -2
  14. package/dist/cli/update-helper-cli.js +28 -6
  15. package/dist/desktop/client-asset-manifest.d.ts +47 -0
  16. package/dist/desktop/client-asset-manifest.js +114 -0
  17. package/dist/desktop/client-asset-stream.d.ts +10 -0
  18. package/dist/desktop/client-asset-stream.js +138 -33
  19. package/dist/desktop/client-assets.d.ts +20 -0
  20. package/dist/desktop/client-assets.js +132 -22
  21. package/dist/desktop/client-response-lifecycle.d.ts +22 -0
  22. package/dist/desktop/client-response-lifecycle.js +233 -0
  23. package/dist/desktop/desktop-host.d.ts +40 -2
  24. package/dist/desktop/desktop-host.js +159 -9
  25. package/dist/framework-source.json +1 -1
  26. package/dist/installer/command-artifact.d.ts +4 -2
  27. package/dist/installer/command-artifact.js +119 -19
  28. package/dist/installer/linux-process-group.d.ts +13 -0
  29. package/dist/installer/linux-process-group.js +58 -0
  30. package/dist/native/darwin-sync.d.ts +7 -0
  31. package/dist/native/darwin-sync.js +43 -0
  32. package/dist/native/desktop-build-hook.js +7 -0
  33. package/dist/native/directory-exchange.d.ts +10 -0
  34. package/dist/native/directory-exchange.js +90 -0
  35. package/dist/native/electrobun-source-patch.d.ts +5 -0
  36. package/dist/native/electrobun-source-patch.js +19 -1
  37. package/dist/native/posix-launcher-build.d.ts +24 -0
  38. package/dist/native/posix-launcher-build.js +232 -0
  39. package/dist/native/posix-tree-removal.d.ts +36 -0
  40. package/dist/native/posix-tree-removal.js +425 -0
  41. package/dist/release/feed-release-cut.js +30 -10
  42. package/dist/release/github-release-cut.js +16 -0
  43. package/dist/release/release-cut.d.ts +8 -1
  44. package/dist/release/release-cut.js +9 -1
  45. package/dist/update-helper.bundle.js +1483 -105
  46. package/dist/updates/channel-update-manager.d.ts +5 -0
  47. package/dist/updates/channel-update-manager.js +13 -1
  48. package/dist/updates/desktop-updater.d.ts +78 -2
  49. package/dist/updates/desktop-updater.js +320 -37
  50. package/dist/updates/launch-environment.d.ts +2 -0
  51. package/dist/updates/launch-environment.js +4 -0
  52. package/dist/updates/native-file-lock.d.ts +15 -0
  53. package/dist/updates/native-file-lock.js +189 -0
  54. package/dist/updates/packaged-launch-admission.d.ts +13 -0
  55. package/dist/updates/packaged-launch-admission.js +45 -0
  56. package/dist/updates/packaged-release-config.d.ts +18 -0
  57. package/dist/updates/packaged-release-config.js +60 -0
  58. package/dist/updates/packaged-update-startup.d.ts +44 -0
  59. package/dist/updates/packaged-update-startup.js +81 -0
  60. package/dist/updates/update-arm.d.ts +9 -8
  61. package/dist/updates/update-arm.js +227 -62
  62. package/dist/updates/update-cleanup-error.d.ts +23 -0
  63. package/dist/updates/update-cleanup-error.js +65 -0
  64. package/dist/updates/update-download-cleanup.d.ts +11 -0
  65. package/dist/updates/update-download-cleanup.js +112 -2
  66. package/dist/updates/update-download-lock.d.ts +20 -0
  67. package/dist/updates/update-download-lock.js +73 -0
  68. package/dist/updates/update-download.d.ts +2 -0
  69. package/dist/updates/update-download.js +7 -3
  70. package/dist/updates/update-generation-lease.d.ts +6 -0
  71. package/dist/updates/update-generation-lease.js +14 -0
  72. package/dist/updates/update-helper.d.ts +11 -2
  73. package/dist/updates/update-helper.js +322 -13
  74. package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
  75. package/dist/updates/update-inherited-launch-lease.js +58 -0
  76. package/dist/updates/update-instance-lease.d.ts +15 -0
  77. package/dist/updates/update-instance-lease.js +25 -0
  78. package/dist/updates/update-launch-gate.d.ts +137 -0
  79. package/dist/updates/update-launch-gate.js +617 -0
  80. package/dist/updates/update-launch.js +3 -1
  81. package/dist/updates/update-lock.d.ts +12 -0
  82. package/dist/updates/update-lock.js +18 -0
  83. package/dist/updates/update-manager.d.ts +2 -0
  84. package/dist/updates/update-manager.js +9 -2
  85. package/dist/updates/update-marker.d.ts +7 -0
  86. package/dist/updates/update-marker.js +62 -0
  87. package/dist/updates/update-preflight-error.d.ts +7 -0
  88. package/dist/updates/update-preflight-error.js +11 -0
  89. package/dist/updates/update-process-fence.d.ts +4 -0
  90. package/dist/updates/update-process-fence.js +85 -73
  91. package/dist/updates/update-process-liveness.d.ts +2 -0
  92. package/dist/updates/update-process-liveness.js +11 -0
  93. package/dist/updates/update-resume.d.ts +37 -3
  94. package/dist/updates/update-resume.js +839 -23
  95. package/dist/updates/update-retention-marker.d.ts +67 -0
  96. package/dist/updates/update-retention-marker.js +165 -0
  97. package/dist/updates/update-retention-plan.d.ts +25 -0
  98. package/dist/updates/update-retention-plan.js +54 -0
  99. package/dist/updates/update-retention-sync.d.ts +34 -0
  100. package/dist/updates/update-retention-sync.js +83 -0
  101. package/dist/updates/update-retirement.d.ts +205 -0
  102. package/dist/updates/update-retirement.js +1485 -0
  103. package/dist/updates/update-shutdown.d.ts +16 -4
  104. package/dist/updates/update-shutdown.js +133 -8
  105. package/dist/updates/update-state-store.d.ts +58 -0
  106. package/dist/updates/update-state-store.js +139 -0
  107. package/dist/updates/update-swap-stage.d.ts +1 -1
  108. package/dist/updates/update-swap-stage.js +85 -14
  109. package/dist/updates/update-swap.d.ts +45 -2
  110. package/dist/updates/update-swap.js +207 -17
  111. package/package.json +31 -1
  112. package/src/appearance/custom-theme-import.ts +96 -14
  113. package/src/appearance/custom-theme-library.ts +5 -0
  114. package/src/appearance/theme-record-adapter.ts +15 -6
  115. package/src/appearance/theme-registry.ts +8 -1
  116. package/src/desktop/client-asset-manifest.ts +207 -0
  117. package/src/desktop/client-asset-stream.ts +193 -32
  118. package/src/desktop/client-assets.ts +210 -19
  119. package/src/desktop/client-response-lifecycle.ts +305 -0
  120. package/src/native/electrobun-posix-launch-lease.patch +398 -0
  121. package/templates/application/README.md +50 -0
  122. package/templates/application/electrobun.config.ts +5 -1
  123. package/templates/application/scripts/build-desktop.ts +4 -0
  124. package/templates/application/src/bun/index.ts +173 -16
  125. package/templates/application/vite.config.ts +112 -6
@@ -0,0 +1,67 @@
1
+ import type { UpdateTreeIdentity } from './update-swap';
2
+ /**
3
+ * A generation-scoped request to prune one exact previous install tree.
4
+ *
5
+ * This record is recovery data, not authorization to remove anything. The caller
6
+ * must validate ownership and prune eligibility while holding the external
7
+ * update lock, then revalidate both identities before any later cleanup.
8
+ */
9
+ export type UpdateRetentionIntent = Readonly<{
10
+ schema: 1;
11
+ phase: 'prune-previous-tree';
12
+ target: string;
13
+ /** Generation whose previousTreeIdentity is the tree being considered. */
14
+ generation: string;
15
+ previousTreeIdentity: UpdateTreeIdentity;
16
+ /** Generation and identity of the install that authorized this intent. */
17
+ installedGeneration: string;
18
+ installedTreeIdentity: UpdateTreeIdentity;
19
+ }>;
20
+ /** Compare all fields that bind an intent to its retained and installed trees. */
21
+ export declare function sameRetentionIntent(left: UpdateRetentionIntent, right: UpdateRetentionIntent): boolean;
22
+ export type UpdateRetentionPublicationResult = Readonly<{
23
+ status: 'published';
24
+ }> | Readonly<{
25
+ status: 'published-with-temporary';
26
+ temporaryPath: string;
27
+ cleanupError: unknown;
28
+ }>;
29
+ export type UpdateRetentionIntentFile = Readonly<{
30
+ intent: UpdateRetentionIntent;
31
+ identity: UpdateTreeIdentity;
32
+ }>;
33
+ export type RemoveUpdateRetentionTemporary = (temporaryPath: string) => Promise<void> | void;
34
+ /** Publication failed before the final link; inspect the temporary path during recovery. */
35
+ export declare class UpdateRetentionPublicationError extends Error {
36
+ readonly temporaryPath: string;
37
+ constructor(temporaryPath: string, cause: unknown);
38
+ }
39
+ /** Return the stable, generation-specific intent path beside the install. */
40
+ export declare function updateRetentionIntentPath(target: string, generation: string): string;
41
+ /**
42
+ * Publish a complete intent atomically without replacing an existing record.
43
+ *
44
+ * The caller must already have validated prune eligibility under its external
45
+ * lock. A failed publication leaves its temporary file untouched for explicit
46
+ * recovery. The result distinguishes a committed marker whose temporary link
47
+ * could not be removed, and callers must handle that outcome explicitly. The
48
+ * optional second argument only removes the temporary path after the commit;
49
+ * it defaults to `unlink`. This guarantees atomic visibility on the local
50
+ * filesystem, not power-loss durability; this function never deletes a tree
51
+ * or interprets an intent.
52
+ */
53
+ export declare function publishUpdateRetentionIntent(intent: UpdateRetentionIntent, removeTemporary?: RemoveUpdateRetentionTemporary): Promise<UpdateRetentionPublicationResult>;
54
+ /**
55
+ * Read and validate the exact intent for this target and generation.
56
+ *
57
+ * `undefined` means the marker does not exist. Malformed records, symlinks,
58
+ * unexpected file types, and I/O failures throw. A valid result still does not
59
+ * grant cleanup authority; the caller must revalidate authorization under lock.
60
+ */
61
+ export declare function readUpdateRetentionIntent(target: string, generation: string): Promise<UpdateRetentionIntent | undefined>;
62
+ /**
63
+ * Read one canonical final marker or publisher temporary and report the opened
64
+ * regular file identity. The latter is used only to verify a temporary hard
65
+ * link before removing that temporary name; it never authorizes tree cleanup.
66
+ */
67
+ export declare function readUpdateRetentionIntentFile(path: string, target: string, generation: string): Promise<UpdateRetentionIntentFile | undefined>;
@@ -0,0 +1,165 @@
1
+ import { link, lstat, open, unlink, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { constants as constants$1 } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ // src/updates/update-retention-marker.ts
6
+ /** Compare all fields that bind an intent to its retained and installed trees. */
7
+ function sameRetentionIntent(left, right) {
8
+ return left.schema === right.schema && left.phase === right.phase && left.target === right.target && left.generation === right.generation && left.installedGeneration === right.installedGeneration && left.previousTreeIdentity !== void 0 && right.previousTreeIdentity !== void 0 && left.installedTreeIdentity !== void 0 && right.installedTreeIdentity !== void 0 && left.previousTreeIdentity.device === right.previousTreeIdentity.device && left.previousTreeIdentity.inode === right.previousTreeIdentity.inode && left.installedTreeIdentity.device === right.installedTreeIdentity.device && left.installedTreeIdentity.inode === right.installedTreeIdentity.inode;
9
+ }
10
+ /** Publication failed before the final link; inspect the temporary path during recovery. */
11
+ var UpdateRetentionPublicationError = class extends Error {
12
+ temporaryPath;
13
+ constructor(temporaryPath, cause) {
14
+ super("Could not publish update retention intent", { cause });
15
+ this.temporaryPath = temporaryPath;
16
+ this.name = "UpdateRetentionPublicationError";
17
+ }
18
+ };
19
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
20
+ var IDENTITY_COMPONENT = /^[1-9]\d{0,19}$/;
21
+ var MAX_MARKER_BYTES = 2048;
22
+ function assertCanonicalTarget(target) {
23
+ if (typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || target.includes("\0")) throw new Error("Invalid update retention target");
24
+ }
25
+ function assertGeneration(generation) {
26
+ if (typeof generation !== "string" || !UUID.test(generation)) throw new Error("Invalid update retention generation");
27
+ }
28
+ function isRecord(value) {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+ function hasExactOwnKeys(value, expected) {
32
+ const actual = Reflect.ownKeys(value);
33
+ return actual.length === expected.length && actual.every((key) => typeof key === "string" && expected.includes(key));
34
+ }
35
+ function isIdentity(value) {
36
+ if (!isRecord(value)) return false;
37
+ return hasExactOwnKeys(value, ["device", "inode"]) && typeof value.device === "string" && IDENTITY_COMPONENT.test(value.device) && typeof value.inode === "string" && IDENTITY_COMPONENT.test(value.inode);
38
+ }
39
+ function parseUpdateRetentionIntent(value, target, generation) {
40
+ if (!isRecord(value)) throw new Error("Invalid update retention intent");
41
+ if (!hasExactOwnKeys(value, [
42
+ "schema",
43
+ "phase",
44
+ "target",
45
+ "generation",
46
+ "previousTreeIdentity",
47
+ "installedGeneration",
48
+ "installedTreeIdentity"
49
+ ]) || value.schema !== 1 || value.phase !== "prune-previous-tree" || value.target !== target || value.generation !== generation || typeof value.installedGeneration !== "string" || !UUID.test(value.installedGeneration) || !isIdentity(value.previousTreeIdentity) || !isIdentity(value.installedTreeIdentity)) throw new Error("Invalid update retention intent");
50
+ return Object.freeze({
51
+ schema: 1,
52
+ phase: "prune-previous-tree",
53
+ target,
54
+ generation,
55
+ previousTreeIdentity: Object.freeze({
56
+ device: value.previousTreeIdentity.device,
57
+ inode: value.previousTreeIdentity.inode
58
+ }),
59
+ installedGeneration: value.installedGeneration,
60
+ installedTreeIdentity: Object.freeze({
61
+ device: value.installedTreeIdentity.device,
62
+ inode: value.installedTreeIdentity.inode
63
+ })
64
+ });
65
+ }
66
+ /** Return the stable, generation-specific intent path beside the install. */
67
+ function updateRetentionIntentPath(target, generation) {
68
+ assertCanonicalTarget(target);
69
+ assertGeneration(generation);
70
+ return join(dirname(target), `.${basename(target)}.framework-prune-${generation}.json`);
71
+ }
72
+ /**
73
+ * Publish a complete intent atomically without replacing an existing record.
74
+ *
75
+ * The caller must already have validated prune eligibility under its external
76
+ * lock. A failed publication leaves its temporary file untouched for explicit
77
+ * recovery. The result distinguishes a committed marker whose temporary link
78
+ * could not be removed, and callers must handle that outcome explicitly. The
79
+ * optional second argument only removes the temporary path after the commit;
80
+ * it defaults to `unlink`. This guarantees atomic visibility on the local
81
+ * filesystem, not power-loss durability; this function never deletes a tree
82
+ * or interprets an intent.
83
+ */
84
+ async function publishUpdateRetentionIntent(intent, removeTemporary = unlink) {
85
+ if (!isRecord(intent)) throw new Error("Invalid update retention intent");
86
+ if (typeof removeTemporary !== "function") throw new Error("Invalid update retention temporary remover");
87
+ const value = parseUpdateRetentionIntent(intent, intent.target, intent.generation);
88
+ const marker = updateRetentionIntentPath(value.target, value.generation);
89
+ const temporary = join(dirname(marker), `.${basename(marker)}.${randomUUID()}.tmp`);
90
+ try {
91
+ await writeFile(temporary, JSON.stringify(value) + "\n", {
92
+ flag: "wx",
93
+ mode: 384
94
+ });
95
+ await link(temporary, marker);
96
+ } catch (cause) {
97
+ throw new UpdateRetentionPublicationError(temporary, cause);
98
+ }
99
+ try {
100
+ await removeTemporary(temporary);
101
+ return { status: "published" };
102
+ } catch (cleanupError) {
103
+ return {
104
+ status: "published-with-temporary",
105
+ temporaryPath: temporary,
106
+ cleanupError
107
+ };
108
+ }
109
+ }
110
+ /**
111
+ * Read and validate the exact intent for this target and generation.
112
+ *
113
+ * `undefined` means the marker does not exist. Malformed records, symlinks,
114
+ * unexpected file types, and I/O failures throw. A valid result still does not
115
+ * grant cleanup authority; the caller must revalidate authorization under lock.
116
+ */
117
+ async function readUpdateRetentionIntent(target, generation) {
118
+ return (await readUpdateRetentionIntentFile(updateRetentionIntentPath(target, generation), target, generation))?.intent;
119
+ }
120
+ /**
121
+ * Read one canonical final marker or publisher temporary and report the opened
122
+ * regular file identity. The latter is used only to verify a temporary hard
123
+ * link before removing that temporary name; it never authorizes tree cleanup.
124
+ */
125
+ async function readUpdateRetentionIntentFile(path, target, generation) {
126
+ const marker = updateRetentionIntentPath(target, generation);
127
+ const temporaryPrefix = `.${basename(marker)}.`;
128
+ const name = basename(path);
129
+ const temporaryId = name.startsWith(temporaryPrefix) && name.endsWith(".tmp") ? name.slice(temporaryPrefix.length, -4) : "";
130
+ const isCanonicalTemporary = dirname(path) === dirname(marker) && join(dirname(marker), name) === path && UUID.test(temporaryId);
131
+ if (path !== marker && !isCanonicalTemporary) throw new Error("Invalid update retention intent path");
132
+ let pathInfo;
133
+ try {
134
+ pathInfo = await lstat(path, { bigint: true });
135
+ } catch (error) {
136
+ if (error.code === "ENOENT") return void 0;
137
+ throw error;
138
+ }
139
+ if (!pathInfo.isFile() || pathInfo.isSymbolicLink() || pathInfo.size < 1n || pathInfo.size > BigInt(MAX_MARKER_BYTES)) throw new Error("Invalid update retention intent file");
140
+ let file;
141
+ try {
142
+ file = await open(path, constants$1.O_RDONLY | (constants$1.O_NOFOLLOW ?? 0) | (constants$1.O_NONBLOCK ?? 0));
143
+ } catch (error) {
144
+ if (error.code === "ENOENT") throw new Error("Update retention intent disappeared during inspection", { cause: error });
145
+ throw error;
146
+ }
147
+ try {
148
+ const info = await file.stat({ bigint: true });
149
+ if (!info.isFile() || info.size < 1n || info.size > BigInt(MAX_MARKER_BYTES) || info.size !== pathInfo.size || info.dev !== pathInfo.dev || info.ino !== pathInfo.ino) throw new Error("Invalid update retention intent file");
150
+ const contents = await file.readFile("utf8");
151
+ if (Buffer.byteLength(contents, "utf8") > MAX_MARKER_BYTES) throw new Error("Invalid update retention intent file");
152
+ const afterRead = await file.stat({ bigint: true });
153
+ if (!afterRead.isFile() || afterRead.dev !== info.dev || afterRead.ino !== info.ino || afterRead.size !== info.size || afterRead.mtimeNs !== info.mtimeNs || afterRead.ctimeNs !== info.ctimeNs) throw new Error("Update retention intent changed during inspection");
154
+ return {
155
+ intent: parseUpdateRetentionIntent(JSON.parse(contents), target, generation),
156
+ identity: {
157
+ device: info.dev.toString(),
158
+ inode: info.ino.toString()
159
+ }
160
+ };
161
+ } finally {
162
+ await file.close();
163
+ }
164
+ }
165
+ export { UpdateRetentionPublicationError, publishUpdateRetentionIntent, readUpdateRetentionIntent, readUpdateRetentionIntentFile, sameRetentionIntent, updateRetentionIntentPath };
@@ -0,0 +1,25 @@
1
+ import type { UpdateTreeIdentity } from './update-swap';
2
+ /** Inputs must be read and validated while holding the update lock. */
3
+ export type RetentionGeneration = Readonly<{
4
+ generation: string;
5
+ installed: UpdateTreeIdentity;
6
+ previous: UpdateTreeIdentity;
7
+ healthy: boolean;
8
+ }>;
9
+ export type RetentionPlan = Readonly<{
10
+ status: 'ready';
11
+ keep: string | null;
12
+ prune: readonly string[];
13
+ }> | Readonly<{
14
+ status: 'recovery-required';
15
+ }>;
16
+ /** Canonical key for validated device/inode pairs used in retention inventories. */
17
+ export declare function retentionIdentityKey(identity: UpdateTreeIdentity): string | undefined;
18
+ /**
19
+ * Select older generations by identity lineage, retaining the current rollback
20
+ * tree. This is a non-destructive planner: it does not prove filesystem
21
+ * ownership, durable health or safe deletion, and is not a cleanup policy.
22
+ * A future cleanup must follow the returned oldest-first order and revalidate
23
+ * ownership and the plan before each deletion.
24
+ */
25
+ export declare function planUpdateRetention(current: UpdateTreeIdentity, generations: readonly RetentionGeneration[]): RetentionPlan;
@@ -0,0 +1,54 @@
1
+ // src/updates/update-retention-plan.ts
2
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3
+ /** Canonical key for validated device/inode pairs used in retention inventories. */
4
+ function retentionIdentityKey(identity) {
5
+ if (!identity || typeof identity.device !== "string" || !/^[1-9]\d{0,19}$/.test(identity.device) || typeof identity.inode !== "string" || !/^[1-9]\d{0,19}$/.test(identity.inode)) return void 0;
6
+ return `${identity.device}:${identity.inode}`;
7
+ }
8
+ /**
9
+ * Select older generations by identity lineage, retaining the current rollback
10
+ * tree. This is a non-destructive planner: it does not prove filesystem
11
+ * ownership, durable health or safe deletion, and is not a cleanup policy.
12
+ * A future cleanup must follow the returned oldest-first order and revalidate
13
+ * ownership and the plan before each deletion.
14
+ */
15
+ function planUpdateRetention(current, generations) {
16
+ const fail = { status: "recovery-required" };
17
+ const currentKey = retentionIdentityKey(current);
18
+ if (!currentKey || !Array.isArray(generations)) return fail;
19
+ if (!generations.length) return {
20
+ status: "ready",
21
+ keep: null,
22
+ prune: []
23
+ };
24
+ const byInstalled = /* @__PURE__ */ new Map();
25
+ const seenPrevious = /* @__PURE__ */ new Set();
26
+ const seenGenerations = /* @__PURE__ */ new Set();
27
+ for (const item of generations) {
28
+ if (!item || !UUID.test(item.generation) || typeof item.healthy !== "boolean") return fail;
29
+ const installed = retentionIdentityKey(item.installed);
30
+ const previous = retentionIdentityKey(item.previous);
31
+ if (!installed || !previous || installed === previous || byInstalled.has(installed) || seenPrevious.has(previous) || seenGenerations.has(item.generation.toLowerCase())) return fail;
32
+ byInstalled.set(installed, item);
33
+ seenPrevious.add(previous);
34
+ seenGenerations.add(item.generation.toLowerCase());
35
+ }
36
+ const chain = [];
37
+ const visited = /* @__PURE__ */ new Set();
38
+ let cursor = currentKey;
39
+ while (byInstalled.has(cursor)) {
40
+ if (visited.has(cursor)) return fail;
41
+ visited.add(cursor);
42
+ const item = byInstalled.get(cursor);
43
+ if (!item.healthy) return fail;
44
+ chain.push(item);
45
+ cursor = retentionIdentityKey(item.previous);
46
+ }
47
+ if (chain.length !== generations.length || !chain.length) return fail;
48
+ return {
49
+ status: "ready",
50
+ keep: chain[0].generation,
51
+ prune: chain.slice(1).toReversed().map((item) => item.generation)
52
+ };
53
+ }
54
+ export { planUpdateRetention, retentionIdentityKey };
@@ -0,0 +1,34 @@
1
+ import { type BigIntStats } from 'node:fs';
2
+ import { type UpdateRetentionIntent } from './update-retention-marker';
3
+ import type { UpdateTreeIdentity } from './update-swap';
4
+ /** The small file-handle surface used by the persistence barrier. */
5
+ type UpdateRetentionSyncHandle = Readonly<{
6
+ fd?: number;
7
+ stat(options: {
8
+ bigint: true;
9
+ }): Promise<BigIntStats>;
10
+ sync(): Promise<void>;
11
+ close(): Promise<void>;
12
+ }>;
13
+ /** Injectable open operation for deterministic filesystem and failure tests. */
14
+ export type UpdateRetentionSyncIO = Readonly<{
15
+ open(path: string, flags: number): Promise<UpdateRetentionSyncHandle>;
16
+ sync?(handle: UpdateRetentionSyncHandle, kind: 'file' | 'directory'): Promise<void>;
17
+ }>;
18
+ /**
19
+ * Request synchronization of one already-published final retention marker.
20
+ *
21
+ * The caller must hold the update lock across this call and any subsequent
22
+ * retention decision. This validates the exact marker through the existing
23
+ * reader, checks its opened file identity, synchronizes the marker and its
24
+ * parent directory, then rechecks both marker content and identity. It never
25
+ * removes a marker or a tree.
26
+ *
27
+ * On macOS arm64, file contents use F_FULLFSYNC and directory entries use
28
+ * F_BARRIERFSYNC. Other supported runtimes use FileHandle.sync(). Calls fail
29
+ * closed on errors or unsupported no-follow/directory-open behavior. Even the
30
+ * macOS barriers cannot prove that storage hardware honored its flush request
31
+ * during a physical power loss.
32
+ */
33
+ export declare function syncUpdateRetentionIntent(intent: UpdateRetentionIntent, io?: UpdateRetentionSyncIO): Promise<UpdateTreeIdentity>;
34
+ export {};
@@ -0,0 +1,83 @@
1
+ import { syncDarwinDescriptor } from "../native/darwin-sync.js";
2
+ import { readUpdateRetentionIntentFile, sameRetentionIntent, updateRetentionIntentPath } from "./update-retention-marker.js";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { constants as constants$1 } from "node:fs";
6
+ // src/updates/update-retention-sync.ts
7
+ var defaultIO = {
8
+ open: async (path, flags) => open(path, flags),
9
+ async sync(handle, kind) {
10
+ if (process.platform === "darwin" && process.arch === "arm64") {
11
+ if (handle.fd === void 0) throw new Error("Update retention descriptor is unavailable for Darwin synchronization");
12
+ syncDarwinDescriptor(handle.fd, kind);
13
+ return;
14
+ }
15
+ await handle.sync();
16
+ }
17
+ };
18
+ async function synchronize(io, handle, kind) {
19
+ if (io.sync) await io.sync(handle, kind);
20
+ else await handle.sync();
21
+ }
22
+ function sameIdentity(left, right) {
23
+ return left.device === right.device && left.inode === right.inode;
24
+ }
25
+ function fileHasIdentity(info, identity) {
26
+ return info.isFile() && info.dev.toString() === identity.device && info.ino.toString() === identity.inode;
27
+ }
28
+ function assertDirectory(info, expected) {
29
+ if (!info.isDirectory() || expected !== void 0 && (info.dev !== expected.dev || info.ino !== expected.ino)) throw new Error("Update retention intent directory changed during sync");
30
+ }
31
+ async function readExpectedMarker(markerPath, intent) {
32
+ const marker = await readUpdateRetentionIntentFile(markerPath, intent.target, intent.generation);
33
+ if (marker === void 0 || !sameRetentionIntent(marker.intent, intent)) throw new Error("Update retention intent does not match the expected final marker");
34
+ return marker.identity;
35
+ }
36
+ /**
37
+ * Request synchronization of one already-published final retention marker.
38
+ *
39
+ * The caller must hold the update lock across this call and any subsequent
40
+ * retention decision. This validates the exact marker through the existing
41
+ * reader, checks its opened file identity, synchronizes the marker and its
42
+ * parent directory, then rechecks both marker content and identity. It never
43
+ * removes a marker or a tree.
44
+ *
45
+ * On macOS arm64, file contents use F_FULLFSYNC and directory entries use
46
+ * F_BARRIERFSYNC. Other supported runtimes use FileHandle.sync(). Calls fail
47
+ * closed on errors or unsupported no-follow/directory-open behavior. Even the
48
+ * macOS barriers cannot prove that storage hardware honored its flush request
49
+ * during a physical power loss.
50
+ */
51
+ async function syncUpdateRetentionIntent(intent, io = defaultIO) {
52
+ const markerPath = updateRetentionIntentPath(intent.target, intent.generation);
53
+ const markerIdentity = await readExpectedMarker(markerPath, intent);
54
+ const parentPath = dirname(markerPath);
55
+ if (typeof constants$1.O_NOFOLLOW !== "number" || typeof constants$1.O_DIRECTORY !== "number" || typeof constants$1.O_NONBLOCK !== "number") throw new Error("Update retention intent synchronization is unsupported on this platform");
56
+ const parentBeforeOpen = await lstat(parentPath, { bigint: true });
57
+ if (!parentBeforeOpen.isDirectory() || parentBeforeOpen.isSymbolicLink()) throw new Error("Invalid update retention intent directory");
58
+ const directory = await io.open(parentPath, constants$1.O_RDONLY | constants$1.O_DIRECTORY | constants$1.O_NOFOLLOW);
59
+ try {
60
+ const directoryIdentity = await directory.stat({ bigint: true });
61
+ assertDirectory(directoryIdentity, parentBeforeOpen);
62
+ const marker = await io.open(markerPath, constants$1.O_RDONLY | constants$1.O_NOFOLLOW | constants$1.O_NONBLOCK);
63
+ try {
64
+ if (!fileHasIdentity(await marker.stat({ bigint: true }), markerIdentity)) throw new Error("Update retention intent changed before synchronization");
65
+ assertDirectory(await lstat(parentPath, { bigint: true }), directoryIdentity);
66
+ if (!fileHasIdentity(await lstat(markerPath, { bigint: true }), markerIdentity)) throw new Error("Update retention intent changed before synchronization");
67
+ if (!sameIdentity(await readExpectedMarker(markerPath, intent), markerIdentity)) throw new Error("Update retention intent changed before synchronization");
68
+ await synchronize(io, marker, "file");
69
+ if (!fileHasIdentity(await marker.stat({ bigint: true }), markerIdentity)) throw new Error("Update retention intent changed during synchronization");
70
+ await synchronize(io, directory, "directory");
71
+ assertDirectory(await directory.stat({ bigint: true }), directoryIdentity);
72
+ if (!sameIdentity(await readExpectedMarker(markerPath, intent), markerIdentity)) throw new Error("Update retention intent changed during synchronization");
73
+ if (!fileHasIdentity(await lstat(markerPath, { bigint: true }), markerIdentity)) throw new Error("Update retention intent changed during synchronization");
74
+ assertDirectory(await lstat(parentPath, { bigint: true }), directoryIdentity);
75
+ return markerIdentity;
76
+ } finally {
77
+ await marker.close();
78
+ }
79
+ } finally {
80
+ await directory.close();
81
+ }
82
+ }
83
+ export { syncUpdateRetentionIntent };
@@ -0,0 +1,205 @@
1
+ import { type ReleaseTrust } from './signed-release';
2
+ import { type RetentionPlan } from './update-retention-plan';
3
+ import { type UpdateRetentionIntent, type UpdateRetentionPublicationResult } from './update-retention-marker';
4
+ import { type UpdateStageState } from './update-state-store';
5
+ import { type UpdateTreeIdentity } from './update-swap';
6
+ export type UpdateHealthAcknowledgement = Readonly<{
7
+ generation: string;
8
+ version: string;
9
+ }>;
10
+ export type UpdateRetentionPruneStep = Readonly<{
11
+ status: 'none' | 'busy' | 'more' | 'pruned' | 'recovery-required';
12
+ removed?: number;
13
+ }>;
14
+ export type UpdateRetentionReconciliationResult = Readonly<{
15
+ status: 'already-clean';
16
+ intent: UpdateRetentionIntent;
17
+ } | {
18
+ status: 'temporary-removed';
19
+ intent: UpdateRetentionIntent;
20
+ temporaryPath: string;
21
+ }>;
22
+ export type UpdateRetentionOrphanPromotionResult = Readonly<{
23
+ status: 'promoted';
24
+ intent: UpdateRetentionIntent;
25
+ temporaryPath: string;
26
+ finalPath: string;
27
+ }>;
28
+ /** A failed promotion may have left the final marker in place; inspect before retrying. */
29
+ export declare class UpdateRetentionOrphanPromotionError extends Error {
30
+ readonly temporaryPath: string;
31
+ readonly finalPath: string;
32
+ readonly publicationState: 'unknown' | 'linked';
33
+ constructor(temporaryPath: string, finalPath: string, publicationState: 'unknown' | 'linked', cause: unknown);
34
+ }
35
+ /** Generation-specific retirement paths, all beside the fixed staging path. */
36
+ export declare function updateRetirementPaths(target: string, generation: string): Readonly<{
37
+ container: string;
38
+ tree: string;
39
+ healthReceipt: string;
40
+ healthTemporaryPrefix: ".healthy-";
41
+ claim: string;
42
+ claimTemporaryPrefix: `${string}.claim-`;
43
+ cleanupMarker: string;
44
+ cleanupMarkerTemporaryPrefix: `.${string}.framework-update-cleanup-`;
45
+ }>;
46
+ export type RetainedUpdateTree = Readonly<{
47
+ generation: string;
48
+ version: string;
49
+ tree: string;
50
+ }>;
51
+ export type RetainedUpdateTrees = Readonly<{
52
+ status: 'none' | 'busy';
53
+ }> | Readonly<{
54
+ status: 'acquired';
55
+ trees: readonly RetainedUpdateTree[];
56
+ release(): Promise<void>;
57
+ }>;
58
+ /**
59
+ * Discover the exact unacknowledged installed generation after staging cleanup.
60
+ * The generation claim is persistent beside the retired tree, so discovery does
61
+ * not depend on a startup return value or log message.
62
+ */
63
+ export declare function findPendingUpdateHealthAcknowledgement(options: {
64
+ target: string;
65
+ currentVersion: string;
66
+ }): Promise<UpdateHealthAcknowledgement | null>;
67
+ /**
68
+ * Fail closed before publishing a new stage while any retention-prune intent,
69
+ * progress marker, temporary, or unknown prune-shaped artifact is present.
70
+ * Uses the same artifact-name check as strict retention inventory and must be
71
+ * called while the per-install update lock is held. It deliberately does not
72
+ * require unrelated retirement history to be valid before a new stage.
73
+ */
74
+ export declare function assertNoUpdateRetentionPruneArtifactsWhileLocked(target: string): Promise<void>;
75
+ /**
76
+ * Plan rollback-tree retention from a complete, read-only filesystem inventory.
77
+ * This does not delete or modify retirement records; callers must revalidate
78
+ * ownership and the returned plan before any future cleanup operation.
79
+ */
80
+ export declare function planValidatedUpdateRetention(options: {
81
+ target: string;
82
+ currentVersion: string;
83
+ }): Promise<RetentionPlan>;
84
+ /**
85
+ * Acquire shared leases on every validated retained generation. Keep the
86
+ * returned leases until all readers and response bodies have finished. A future
87
+ * deletion implementation must hold the update lock and the same generation's
88
+ * exclusive lease while it revalidates and removes that generation.
89
+ */
90
+ export declare function acquireRetainedUpdateTrees(options: {
91
+ target: string;
92
+ currentVersion: string;
93
+ }): Promise<RetainedUpdateTrees>;
94
+ /**
95
+ * Acquire retained generations while the caller holds the per-install update
96
+ * lock. A staged candidate is accepted only after its caller has run trusted
97
+ * resume validation; this function repeats the stage identity and descriptor
98
+ * checks before permitting the retention inventory.
99
+ */
100
+ export declare function acquireRetainedUpdateTreesWhileLocked(options: {
101
+ target: string;
102
+ currentVersion: string;
103
+ validatedStagedVersion?: string;
104
+ stagedTrust?: ReleaseTrust;
105
+ }): Promise<RetainedUpdateTrees>;
106
+ /**
107
+ * Inspect one published retention intent against the current install while
108
+ * holding the update lock. This validates recovery data only; it never changes
109
+ * the filesystem or grants deletion authority.
110
+ */
111
+ export declare function inspectUpdateRetentionCleanup(options: {
112
+ target: string;
113
+ currentVersion: string;
114
+ generation: string;
115
+ }): Promise<UpdateRetentionIntent | null>;
116
+ /**
117
+ * Request synchronization of a freshly validated marker under the update lock.
118
+ * This does not establish hardware-level durability or authorize deletion.
119
+ */
120
+ export declare function syncValidatedUpdateRetentionCleanup(options: {
121
+ target: string;
122
+ currentVersion: string;
123
+ generation: string;
124
+ }): Promise<UpdateTreeIdentity>;
125
+ /**
126
+ * Promote one publisher temporary left by an interrupted intent publication.
127
+ * Under the update lock this requires exactly one canonical temporary, no
128
+ * final marker, and no other retention artifacts, then validates the bounded
129
+ * file and oldest eligible cleanup plan twice before a no-replace hard link.
130
+ * It leaves both names in place for reconcileUpdateRetentionCleanup. If the
131
+ * link call fails, whether a final name was created is treated as unknown; if
132
+ * post-link validation fails, the link is known to exist. Both failures
133
+ * preserve every path for inspection. This operation makes no power-loss
134
+ * durability claim and never removes a retirement tree or marker.
135
+ */
136
+ export declare function promoteOrphanUpdateRetentionCleanup(options: {
137
+ target: string;
138
+ currentVersion: string;
139
+ generation: string;
140
+ }): Promise<UpdateRetentionOrphanPromotionResult>;
141
+ /**
142
+ * Reconcile only the publisher's extra hard link after validating the final
143
+ * intent against a fresh retention plan under the update lock. This never
144
+ * deletes a final marker, retirement tree, claim, or receipt, and makes no
145
+ * power-loss durability claim.
146
+ */
147
+ export declare function reconcileUpdateRetentionCleanup(options: {
148
+ target: string;
149
+ currentVersion: string;
150
+ generation: string;
151
+ }): Promise<UpdateRetentionReconciliationResult>;
152
+ /**
153
+ * Record the oldest eligible cleanup candidate while holding the update lock.
154
+ * This WIP operation does not delete data or grant authority to a later caller.
155
+ * Intent publication is not yet power-loss durable.
156
+ */
157
+ export declare function beginUpdateRetentionCleanup(options: {
158
+ target: string;
159
+ currentVersion: string;
160
+ }): Promise<Readonly<{
161
+ intent: UpdateRetentionIntent;
162
+ publication: UpdateRetentionPublicationResult;
163
+ }> | null>;
164
+ /**
165
+ * Make one explicit, bounded prune step for an already-published retention
166
+ * intent. Ordinary inventory readers fail closed while this progress record
167
+ * exists. Calls serialize under the install lock, then take the generation's
168
+ * exclusive lease before inspecting or changing its retired tree.
169
+ *
170
+ * This currently supports only the tested macOS ARM64 directory-relative
171
+ * remover. It requests file and directory synchronization before destructive
172
+ * transitions, but those calls do not prove hardware persistence or recovery
173
+ * after power loss. Callers must invoke this explicitly; startup and updater
174
+ * flows do not prune automatically.
175
+ */
176
+ export declare function pruneUpdateRetentionStep(options: {
177
+ target: string;
178
+ currentVersion: string;
179
+ generation: string;
180
+ maxOperations?: number;
181
+ }): Promise<UpdateRetentionPruneStep>;
182
+ /** Explicitly acknowledge an exact installed generation after app-owned readiness checks. */
183
+ export declare function acknowledgeRetiredUpdateHealthy(options: {
184
+ target: string;
185
+ acknowledgement: UpdateHealthAcknowledgement;
186
+ }): Promise<void>;
187
+ /** Reconcile the exact unlink/rmdir completion boundary while holding the install lock. */
188
+ export declare function reconcileRetirementCleanupMarkerWhileLocked(options: {
189
+ target: string;
190
+ staging: string;
191
+ currentVersion: string;
192
+ }): Promise<'none' | 'updated' | 'recovery-required'>;
193
+ /**
194
+ * Reconcile a completed exchange while the stable per-install lock is held.
195
+ * The old app tree is moved without replacement into a UUID-owned container;
196
+ * it is never modified or deleted here. Atomic rename publication protects
197
+ * against process crashes, but this protocol makes no power-loss claim.
198
+ * Health is recorded only after an explicit host call; app-owned readiness
199
+ * criteria and quarantine retention/cleanup policy remain WIP.
200
+ */
201
+ export declare function retireCompletedUpdateWhileLocked(options: {
202
+ target: string;
203
+ staging: string;
204
+ state: UpdateStageState;
205
+ }): Promise<boolean>;