@amalgm/shell 0.1.163 → 0.1.164-main.34182640231

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 (90) hide show
  1. package/PURPOSE.md +68 -6
  2. package/README.md +58 -11
  3. package/config/releases/trust/runtime/main.root.json +84 -0
  4. package/config/releases/trust/runtime/preview.root.json +84 -0
  5. package/dist/boot.js +28 -20
  6. package/dist/boot.js.map +1 -1
  7. package/dist/cli.js +7 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/content-cache-index.js +2 -2
  10. package/dist/content-cache-index.js.map +1 -1
  11. package/dist/detection/runtime.js +2 -2
  12. package/dist/detection/runtime.js.map +1 -1
  13. package/dist/entity-apply-host.js +2 -2
  14. package/dist/entity-apply-host.js.map +1 -1
  15. package/dist/entity-apply-store.d.ts +2 -1
  16. package/dist/entity-apply-store.js +52 -37
  17. package/dist/entity-apply-store.js.map +1 -1
  18. package/dist/installation/lease.js +2 -2
  19. package/dist/installation/lease.js.map +1 -1
  20. package/dist/installation/ownership.js +2 -2
  21. package/dist/installation/ownership.js.map +1 -1
  22. package/dist/machine-host.d.ts +1 -0
  23. package/dist/machine-host.js +56 -31
  24. package/dist/machine-host.js.map +1 -1
  25. package/dist/process-lifecycle.d.ts +1 -3
  26. package/dist/process-lifecycle.js +10 -0
  27. package/dist/process-lifecycle.js.map +1 -1
  28. package/dist/pty-host.d.ts +1 -1
  29. package/dist/pty-host.js +70 -21
  30. package/dist/pty-host.js.map +1 -1
  31. package/dist/service/cli.js +50 -9
  32. package/dist/service/cli.js.map +1 -1
  33. package/dist/service/control.d.ts +10 -1
  34. package/dist/service/control.js +1 -1
  35. package/dist/service/control.js.map +1 -1
  36. package/dist/service/keepalive.d.ts +10 -3
  37. package/dist/service/keepalive.js +267 -29
  38. package/dist/service/keepalive.js.map +1 -1
  39. package/dist/service/recovery.d.ts +27 -0
  40. package/dist/service/recovery.js +58 -0
  41. package/dist/service/recovery.js.map +1 -0
  42. package/dist/service/systemd-unit.d.ts +7 -0
  43. package/dist/service/systemd-unit.js +43 -0
  44. package/dist/service/systemd-unit.js.map +1 -0
  45. package/dist/service/systemd.d.ts +1 -5
  46. package/dist/service/systemd.js +9 -31
  47. package/dist/service/systemd.js.map +1 -1
  48. package/dist/service/windows-action.d.ts +9 -0
  49. package/dist/service/windows-action.js +55 -0
  50. package/dist/service/windows-action.js.map +1 -0
  51. package/dist/service/windows-task.d.ts +1 -8
  52. package/dist/service/windows-task.js +4 -40
  53. package/dist/service/windows-task.js.map +1 -1
  54. package/dist/service/windows.js +3 -3
  55. package/dist/service/windows.js.map +1 -1
  56. package/dist/sqlite.d.ts +4 -0
  57. package/dist/sqlite.js +16 -0
  58. package/dist/sqlite.js.map +1 -0
  59. package/dist/updates/artifacts.d.ts +40 -0
  60. package/dist/updates/artifacts.js +299 -0
  61. package/dist/updates/artifacts.js.map +1 -0
  62. package/dist/updates/bootstrap.d.ts +48 -0
  63. package/dist/updates/bootstrap.js +384 -0
  64. package/dist/updates/bootstrap.js.map +1 -0
  65. package/dist/updates/controller.d.ts +66 -0
  66. package/dist/updates/controller.js +322 -0
  67. package/dist/updates/controller.js.map +1 -0
  68. package/dist/updates/isolated-command-lifetime.d.ts +1 -0
  69. package/dist/updates/isolated-command-lifetime.js +63 -0
  70. package/dist/updates/isolated-command-lifetime.js.map +1 -0
  71. package/dist/updates/store.d.ts +41 -0
  72. package/dist/updates/store.js +80 -0
  73. package/dist/updates/store.js.map +1 -0
  74. package/dist/updates/trust.d.ts +20 -0
  75. package/dist/updates/trust.js +138 -0
  76. package/dist/updates/trust.js.map +1 -0
  77. package/dist/user-ground-host.d.ts +1 -1
  78. package/dist/user-ground-host.js +3 -3
  79. package/dist/user-ground-host.js.map +1 -1
  80. package/dist/watching/host.js +4 -2
  81. package/dist/watching/host.js.map +1 -1
  82. package/dist/workspace-add-staging.js +2 -2
  83. package/dist/workspace-add-staging.js.map +1 -1
  84. package/examinations/fixtures/machine-control-plane.js +57 -0
  85. package/examinations/fixtures/private-wire-authority.js +1065 -0
  86. package/examinations/native-service.mjs +92 -0
  87. package/examinations/network-view.mjs +202 -0
  88. package/examinations/runtime-upgrade.native-test.mjs +198 -0
  89. package/npm-shrinkwrap.json +2104 -191
  90. package/package.json +94 -13
@@ -0,0 +1,322 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import { existsSync } from 'node:fs';
4
+ import { beginManagedUpdate, completeManagedUpdateEffect, createManagedUpdateState, desireManagedRuntimeRelease, managedUpdateEffect, retainedManagedReleaseDigests, } from '@amalgm/core/supervision';
5
+ import { acquireProcessLease } from '../installation/lease.js';
6
+ import { atomicJson } from '../filesystem.js';
7
+ import { readRegistration, writeRegistration } from '../service/registration.js';
8
+ import { collectAbandonedUpdateWork, collectRuntimeArtifacts, managedPackage, RuntimeDownloadError, stageRuntime } from './artifacts.js';
9
+ import { installedPackage, observedRuntimeFormats, runtimeHost, UpdateStore } from './store.js';
10
+ import { RELEASE_ORIGIN, RuntimeTrust } from './trust.js';
11
+ const reason = (error) => String(error instanceof Error ? error.message : error).replace(/[\x00-\x1f]/g, ' ').slice(0, 1_024) || 'Runtime update effect failed';
12
+ /** Core is the only transition owner. This host performs one persisted effect
13
+ * at a time; release notifications can update desired without changing it. */
14
+ export class RuntimeUpdates {
15
+ identity;
16
+ effects;
17
+ store;
18
+ abort = new AbortController();
19
+ trust;
20
+ state;
21
+ job = null;
22
+ discovery = null;
23
+ notifications = null;
24
+ changed = true;
25
+ workGeneration = 0;
26
+ wake = null;
27
+ replacing = false;
28
+ registration;
29
+ constructor(identity, effects) {
30
+ this.identity = identity;
31
+ this.effects = effects;
32
+ this.registration = readRegistration(identity);
33
+ this.store = new UpdateStore(identity);
34
+ try {
35
+ this.state = this.store.state(identity.binding, runtimeHost());
36
+ this.trust = new RuntimeTrust(this.store, this.abort.signal);
37
+ this.restoreInterruptedLaunch();
38
+ if (this.state && !this.state.transaction)
39
+ this.projectActive();
40
+ }
41
+ catch (error) {
42
+ this.store.close();
43
+ throw error;
44
+ }
45
+ }
46
+ static enabled(identity) {
47
+ return identity.binding.runtimeLabel !== 'local' && managedPackage() && existsSync(join(identity.serviceDir, 'bootstrap.mjs'));
48
+ }
49
+ get permitsOrdinaryRuntime() {
50
+ return this.state === null || this.state.activeHealthy && (!this.state.transaction || ['stage', 'drain'].includes(this.state.transaction.phase));
51
+ }
52
+ get status() {
53
+ return this.state ? { active: this.state.active.target.id, desired: this.state.desired.target.id,
54
+ phase: this.state.transaction?.phase ?? 'current', quarantine: this.state.quarantine } : { phase: 'verifying-installed-baseline' };
55
+ }
56
+ start() {
57
+ this.job = this.run();
58
+ this.notifications = this.listen();
59
+ }
60
+ async close() {
61
+ this.abort.abort();
62
+ this.wake?.();
63
+ await Promise.allSettled([this.job, this.notifications, this.discovery]);
64
+ this.store.close();
65
+ }
66
+ persist(next, launch) {
67
+ if (next === this.state && !launch)
68
+ return;
69
+ this.store.atomic(() => {
70
+ this.store.write('policy', JSON.stringify(next));
71
+ if (launch)
72
+ this.store.write('launch', JSON.stringify(launch));
73
+ });
74
+ this.state = next;
75
+ this.effects.changed();
76
+ this.notifyWork();
77
+ }
78
+ launch() { return JSON.parse(this.store.read('launch')); }
79
+ command(release) {
80
+ const root = this.store.read(`artifact:${release.digest}`);
81
+ if (!root)
82
+ throw new Error('The release has no verified immutable package');
83
+ return { node: this.registration.node, bin: join(root, 'dist/main.js'), args: [...this.registration.keepalive_args] };
84
+ }
85
+ /** Registration and the shared CLI pointer are projections of the committed
86
+ * journal. Boot repairs interruption after policy/launcher commit. */
87
+ projectActive() {
88
+ const active = this.state.active;
89
+ const current = this.command(active);
90
+ const registration = readRegistration(this.identity);
91
+ writeRegistration(this.identity, { ...registration, node: current.node, bin: current.bin,
92
+ package_root: this.store.read(`artifact:${active.digest}`), package_version: active.target.release.units[0].artifact.version });
93
+ atomicJson(join(this.identity.home, '.amalgm/runtime-packages/shell', this.identity.binding.runtimeLabel, 'current.json'), { schema: 1, runtimeLabel: this.identity.binding.runtimeLabel, version: active.target.release.units[0].artifact.version, node: current.node, bin: current.bin });
94
+ }
95
+ sameCode(release) {
96
+ const pkg = installedPackage(this.effects.packageRoot);
97
+ const artifact = release.target.release.units[0].artifact;
98
+ return pkg.version === artifact.version && pkg.amalgmSource?.commit === artifact.source.commit;
99
+ }
100
+ restoreInterruptedLaunch() {
101
+ if (!this.state)
102
+ return;
103
+ const t = this.state.transaction;
104
+ if (!t) {
105
+ if (!this.sameCode(this.state.active))
106
+ throw new Error('The controller is not the committed runtime release');
107
+ return;
108
+ }
109
+ const launch = this.launch();
110
+ if ((launch.pending?.recoveryAttempted || this.sameCode(t.previous) && !this.sameCode(t.candidate))
111
+ && ['start', 'probe'].includes(t.phase)) {
112
+ const effect = managedUpdateEffect(this.state, Math.max(Date.now(), t.notBefore));
113
+ if (effect)
114
+ this.persist(completeManagedUpdateEffect(this.state, effect.token, { type: 'failed', reason: 'Candidate controller exited before committing healthy probation' }, Math.max(Date.now(), t.notBefore)));
115
+ }
116
+ if (![t.previous, t.candidate].some(release => this.sameCode(release)))
117
+ throw new Error('The controller is outside its persisted update transaction');
118
+ }
119
+ notifyWork() { this.workGeneration++; this.wake?.(); }
120
+ signal() { this.changed = true; this.notifyWork(); }
121
+ async wait(milliseconds) {
122
+ if (this.abort.signal.aborted)
123
+ return;
124
+ await new Promise(resolve => { const timer = setTimeout(resolve, milliseconds); this.wake = () => { clearTimeout(timer); resolve(); }; });
125
+ this.wake = null;
126
+ }
127
+ async discover() {
128
+ if (this.discovery)
129
+ return this.discovery;
130
+ this.discovery = (async () => {
131
+ try {
132
+ if (!this.state) {
133
+ const installed = installedPackage(this.effects.packageRoot);
134
+ const baseline = await this.trust.baseline(installed.version);
135
+ const immutable = await stageRuntime(this.identity, baseline, this.registration.node, this.abort.signal, this.effects.packageRoot);
136
+ this.store.write(`artifact:${baseline.digest}`, immutable);
137
+ this.persist(createManagedUpdateState(this.identity.binding, runtimeHost(), baseline, 1));
138
+ }
139
+ const current = await this.trust.current(this.state.desired);
140
+ this.persist(desireManagedRuntimeRelease(this.state, current.target, current.digest));
141
+ }
142
+ catch (error) {
143
+ if (!this.abort.signal.aborted)
144
+ this.effects.log(`Runtime discovery: ${reason(error)}`);
145
+ }
146
+ })().finally(() => { this.discovery = null; this.notifyWork(); });
147
+ return this.discovery;
148
+ }
149
+ async run() {
150
+ try {
151
+ await collectAbandonedUpdateWork(this.identity);
152
+ }
153
+ catch (error) {
154
+ this.effects.log(`Runtime scratch collection: ${reason(error)}`);
155
+ }
156
+ while (!this.abort.signal.aborted && !this.replacing) {
157
+ const observedWork = this.workGeneration;
158
+ try {
159
+ // A hint received during a refresh remains pending until that refresh
160
+ // completes. Its verified result independently wakes effect execution.
161
+ if (this.changed && !this.discovery) {
162
+ this.changed = false;
163
+ void this.discover();
164
+ }
165
+ if (this.state) {
166
+ this.persist(beginManagedUpdate(this.state, Date.now()));
167
+ const effect = managedUpdateEffect(this.state, Date.now());
168
+ if (effect)
169
+ await this.perform(effect.token);
170
+ }
171
+ }
172
+ catch (error) {
173
+ if (!this.abort.signal.aborted)
174
+ this.effects.log(`Runtime reconciliation: ${reason(error)}`);
175
+ }
176
+ // State or hints can arrive while an effect is awaited, before a waiter
177
+ // exists. Observe that work before parking on a future timer.
178
+ if (this.workGeneration !== observedWork)
179
+ continue;
180
+ const pending = this.state?.transaction;
181
+ await this.wait(pending && pending.phase !== 'parked' ? Math.max(250, pending.notBefore - Date.now()) : 5 * 60_000);
182
+ }
183
+ }
184
+ async fence() {
185
+ await this.effects.pause();
186
+ const scope = createHash('sha256').update(JSON.stringify([this.identity.binding, this.identity.user])).digest('hex');
187
+ const file = join(this.identity.home, '.amalgm', 'owners', `${scope}.sqlite`);
188
+ const deadline = Date.now() + 30_000;
189
+ for (;;) {
190
+ const lease = acquireProcessLease(file);
191
+ if (lease) {
192
+ try {
193
+ return observedRuntimeFormats(this.identity.serviceDir);
194
+ }
195
+ finally {
196
+ lease.close();
197
+ }
198
+ }
199
+ if (this.abort.signal.aborted || Date.now() >= deadline)
200
+ throw new Error('The prior runtime has not released installation ownership');
201
+ await this.wait(50);
202
+ }
203
+ }
204
+ async perform(token) {
205
+ const effect = managedUpdateEffect(this.state, Date.now());
206
+ if (!effect || effect.token !== token)
207
+ return;
208
+ const t = effect.transaction;
209
+ let result;
210
+ try {
211
+ if (t.phase === 'stage') {
212
+ const root = await stageRuntime(this.identity, t.candidate, this.registration.node, this.abort.signal);
213
+ this.store.write(`artifact:${t.candidate.digest}`, root);
214
+ result = { type: 'staged' };
215
+ }
216
+ else if (t.phase === 'drain') {
217
+ await this.effects.pause();
218
+ result = { type: 'drained' };
219
+ }
220
+ else if (t.phase === 'fence' || t.phase === 'recovery-fence') {
221
+ result = { type: 'fenced', epoch: t.phase === 'fence' ? t.previousEpoch : t.epoch, schemas: await this.fence() };
222
+ }
223
+ else if (t.phase === 'start' || t.phase === 'recovery-start') {
224
+ const target = t.phase === 'start' ? t.candidate : t.previous;
225
+ if (!this.sameCode(target)) {
226
+ const launch = this.launch();
227
+ if (!launch.pending)
228
+ launch.pending = { token, candidate: this.command(t.candidate), recovery: this.command(t.previous), attempted: false, recoveryAttempted: false };
229
+ this.persist(this.state, launch);
230
+ this.replacing = true;
231
+ this.effects.replace();
232
+ return;
233
+ }
234
+ await this.effects.start();
235
+ result = { type: 'started', epoch: t.phase === 'start' ? t.epoch : t.recoveryEpoch };
236
+ }
237
+ else if (t.phase === 'probe' || t.phase === 'recovery-probe') {
238
+ await this.effects.probe();
239
+ result = { type: 'healthy', epoch: t.phase === 'probe' ? t.epoch : t.recoveryEpoch };
240
+ }
241
+ else
242
+ return;
243
+ }
244
+ catch (error) {
245
+ if (this.abort.signal.aborted)
246
+ return;
247
+ // Network or installation failure cannot affect the still-running active
248
+ // release. A failed candidate remains quarantined until a newer target.
249
+ result = { type: t.phase === 'stage' && error instanceof RuntimeDownloadError ? 'retry' : 'failed', reason: reason(error) };
250
+ }
251
+ const previous = this.state;
252
+ const next = completeManagedUpdateEffect(previous, token, result, Date.now());
253
+ let launch;
254
+ if (!next.transaction || next.transaction.phase === 'parked') {
255
+ launch = this.launch();
256
+ launch.current = this.command(next.active);
257
+ launch.pending = null;
258
+ }
259
+ this.persist(next, launch);
260
+ if (next.transaction?.phase === 'parked')
261
+ await this.effects.pause();
262
+ if (!next.transaction) {
263
+ this.projectActive();
264
+ await collectRuntimeArtifacts(this.identity, retainedManagedReleaseDigests(next));
265
+ }
266
+ }
267
+ async listen() {
268
+ let backoff = 1_000;
269
+ const fallback = setInterval(() => this.signal(), 5 * 60_000);
270
+ fallback.unref();
271
+ try {
272
+ while (!this.abort.signal.aborted) {
273
+ const connection = new AbortController();
274
+ let idle;
275
+ const reset = () => { clearTimeout(idle); idle = setTimeout(() => connection.abort(), 75_000); };
276
+ try {
277
+ reset();
278
+ const response = await fetch(`${RELEASE_ORIGIN}/trust/runtime/${this.identity.binding.runtimeLabel}/events`, {
279
+ redirect: 'error', headers: { accept: 'text/event-stream' }, signal: AbortSignal.any([this.abort.signal, connection.signal])
280
+ });
281
+ if (!response.ok || !response.body || !response.headers.get('content-type')?.startsWith('text/event-stream'))
282
+ throw new Error('Release notifications unavailable');
283
+ this.signal();
284
+ backoff = 1_000;
285
+ const decoder = new TextDecoder();
286
+ let pending = '';
287
+ for await (const chunk of response.body) {
288
+ reset();
289
+ pending += decoder.decode(chunk, { stream: true }).replace(/\r/g, '');
290
+ if (pending.length > 16_384)
291
+ throw new Error('Release notification exceeded its bound');
292
+ let end;
293
+ while ((end = pending.indexOf('\n\n')) >= 0) {
294
+ const event = pending.slice(0, end);
295
+ pending = pending.slice(end + 2);
296
+ if (/^event: (ready|promotion)$/m.test(event))
297
+ this.signal();
298
+ }
299
+ }
300
+ }
301
+ catch { /* Signed current-state reads remain the authority while offline. */ }
302
+ finally {
303
+ clearTimeout(idle);
304
+ connection.abort();
305
+ }
306
+ if (!this.abort.signal.aborted)
307
+ await new Promise(resolve => {
308
+ const timer = setTimeout(done, backoff);
309
+ const abort = () => done();
310
+ function done() { clearTimeout(timer); thisAbort.removeEventListener('abort', abort); resolve(); }
311
+ const thisAbort = this.abort.signal;
312
+ thisAbort.addEventListener('abort', abort, { once: true });
313
+ });
314
+ backoff = Math.min(backoff * 2, 60_000);
315
+ }
316
+ }
317
+ finally {
318
+ clearInterval(fallback);
319
+ }
320
+ }
321
+ }
322
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../../src/updates/controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EACL,kBAAkB,EAAE,2BAA2B,EAAE,wBAAwB,EAAE,2BAA2B,EACtG,mBAAmB,EAAE,6BAA6B,GAEnD,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAA2C,MAAM,4BAA4B,CAAC;AAC1H,OAAO,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,cAAc,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzI,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAChG,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAY1D,MAAM,MAAM,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,cAAc,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,EAAE,CAAC,IAAI,EAAE,CAAC;wBAC3B,SAAS,IAAI,KAAK,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;wBAClG,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;wBAAC,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAClG,CAAC,CAAC,CAAC;gBACH,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC;gBAAS,CAAC;YAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAAC,CAAC;IACxC,CAAC;CACF"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ /** A staging command owns a native lease and a separate lifetime observer.
2
+ * The observer can stop this exact process when its parent pipe closes or its
3
+ * deadline expires, even while the command's main JavaScript thread is busy.
4
+ * Package lifecycle scripts remain npm-owned effects of the examined graph. */
5
+ import { createConnection } from 'node:net';
6
+ import { isAbsolute, toNamespacedPath } from 'node:path';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { isMainThread, parentPort, Worker, workerData } from 'node:worker_threads';
9
+ function lifetime(value) {
10
+ const entry = value;
11
+ if (!entry || typeof entry.file !== 'string' || !isAbsolute(entry.file) || entry.file.includes('\0')
12
+ || !Number.isSafeInteger(entry.timeout) || entry.timeout < 1 || entry.timeout > 600_000
13
+ || !Number.isSafeInteger(entry.port) || entry.port < 1 || entry.port > 65535
14
+ || typeof entry.token !== 'string' || !/^[a-f0-9]{64}$/.test(entry.token))
15
+ throw new Error('Invalid isolated command lifetime');
16
+ return entry;
17
+ }
18
+ if (isMainThread) {
19
+ const input = lifetime(JSON.parse(process.env.AMALGM_ISOLATED_COMMAND_LIFETIME ?? 'null'));
20
+ delete process.env.AMALGM_ISOLATED_COMMAND_LIFETIME;
21
+ // This observer belongs to this command, so Worker/fork must inherit the
22
+ // command's own Node options without inheriting our preload admission.
23
+ const injected = process.execArgv.indexOf(import.meta.url);
24
+ if (injected > 0 && process.execArgv[injected - 1] === '--import')
25
+ process.execArgv.splice(injected - 1, 2);
26
+ const worker = new Worker(new URL(import.meta.url), { workerData: input });
27
+ await new Promise((resolve, reject) => {
28
+ worker.once('error', error => { reject(error); process.kill(process.pid, 'SIGKILL'); });
29
+ worker.once('exit', () => process.kill(process.pid, 'SIGKILL'));
30
+ worker.once('message', () => {
31
+ // Observation must not prevent an otherwise completed npm/preflight
32
+ // process from exiting naturally and releasing its native lease.
33
+ worker.unref();
34
+ resolve();
35
+ });
36
+ });
37
+ }
38
+ else {
39
+ const input = lifetime(workerData);
40
+ const stop = () => process.kill(process.pid, 'SIGKILL');
41
+ setTimeout(stop, input.timeout);
42
+ // The parent creates this directory before spawning. Never recreate a
43
+ // directory another controller has already proved abandoned and collected.
44
+ const lease = new DatabaseSync(toNamespacedPath(input.file));
45
+ lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;');
46
+ process.once('exit', () => lease.close());
47
+ // A dedicated stream has one lifetime owner and cancels cleanly when an
48
+ // unref'ed observer is terminated during normal process shutdown.
49
+ const pipe = createConnection({ host: '127.0.0.1', port: input.port });
50
+ pipe.once('end', stop);
51
+ pipe.once('close', stop);
52
+ pipe.once('error', stop);
53
+ pipe.once('connect', () => pipe.write(input.token + '\n'));
54
+ let admission = '';
55
+ pipe.on('data', bytes => {
56
+ admission += bytes.toString('utf8');
57
+ if (admission.length > 6 || !'start\n'.startsWith(admission))
58
+ stop();
59
+ else if (admission === 'start\n')
60
+ parentPort.postMessage('ready');
61
+ });
62
+ }
63
+ //# sourceMappingURL=isolated-command-lifetime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolated-command-lifetime.js","sourceR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{ type ManagedHost, type ManagedUpdateState } from '@amalgm/core/supervision';
3
+ import type { RuntimeBinding } from '@amalgm/core/binding';
4
+ import type { ServiceIdentity } from '../service/registration.js';
5
+ export declare const RUNTIME_FORMAT: Readonly<{
6
+ id: "installation";
7
+ reads: {
8
+ min: number;
9
+ max: number;
10
+ };
11
+ writes: 1;
12
+ }>;
13
+ export declare const CONTROLLER_PROTOCOL = 1;
14
+ export declare const runtimeHost: () => ManagedHost;
15
+ export declare const packageRoot: string;
16
+ /** The bootstrap and controller use the same native SQLite transaction boundary.
17
+ * The installation controller lease serializes policy writers. */
18
+ export declare class UpdateStore {
19
+ readonly identity: ServiceIdentity;
20
+ readonly database: DatabaseSync;
21
+ constructor(identity: ServiceIdentity);
22
+ read(key: string): string | null;
23
+ write(key: string, value: string): void;
24
+ atomic<T>(effect: () => T): T;
25
+ state(binding: RuntimeBinding, host: ManagedHost): ManagedUpdateState | null;
26
+ close(): void;
27
+ }
28
+ /** Schema 1 names the complete currently shipped installation format, including
29
+ * its locked SDK stores. Future writers must advance this contract before an
30
+ * incompatible migration; they never overwrite an unreadable receipt. */
31
+ export declare function admitRuntimeFormat(serviceDir: string): void;
32
+ export declare function observedRuntimeFormats(serviceDir: string): Readonly<Record<string, number>>;
33
+ export declare function installedPackage(root?: string): {
34
+ name: string;
35
+ version: string;
36
+ amalgmSource?: {
37
+ repository: string;
38
+ branch: string;
39
+ commit: string;
40
+ };
41
+ };
@@ -0,0 +1,80 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, toNamespacedPath } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { restoreManagedUpdateState, } from '@amalgm/core/supervision';
6
+ export const RUNTIME_FORMAT = Object.freeze({ id: 'installation', reads: { min: 1, max: 1 }, writes: 1 });
7
+ export const CONTROLLER_PROTOCOL = 1;
8
+ export const runtimeHost = () => ({ controllerProtocol: CONTROLLER_PROTOCOL,
9
+ nodeMajor: Number(process.versions.node.split('.')[0]), platform: `${process.platform}-${process.arch}` });
10
+ export const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
11
+ /** The bootstrap and controller use the same native SQLite transaction boundary.
12
+ * The installation controller lease serializes policy writers. */
13
+ export class UpdateStore {
14
+ identity;
15
+ database;
16
+ constructor(identity) {
17
+ this.identity = identity;
18
+ mkdirSync(identity.serviceDir, { recursive: true, mode: 0o700 });
19
+ this.database = new DatabaseSync(toNamespacedPath(join(identity.serviceDir, 'updates.sqlite')));
20
+ this.database.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; CREATE TABLE IF NOT EXISTS update_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);');
21
+ }
22
+ read(key) {
23
+ return this.database.prepare('SELECT value FROM update_state WHERE key = ?').get(key)?.value ?? null;
24
+ }
25
+ write(key, value) {
26
+ this.database.prepare('INSERT INTO update_state VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
27
+ }
28
+ atomic(effect) {
29
+ this.database.exec('BEGIN IMMEDIATE');
30
+ try {
31
+ const result = effect();
32
+ this.database.exec('COMMIT');
33
+ return result;
34
+ }
35
+ catch (error) {
36
+ this.database.exec('ROLLBACK');
37
+ throw error;
38
+ }
39
+ }
40
+ state(binding, host) {
41
+ const bytes = this.read('policy');
42
+ return bytes === null ? null : restoreManagedUpdateState(JSON.parse(bytes), binding, host);
43
+ }
44
+ close() { this.database.close(); }
45
+ }
46
+ /** Schema 1 names the complete currently shipped installation format, including
47
+ * its locked SDK stores. Future writers must advance this contract before an
48
+ * incompatible migration; they never overwrite an unreadable receipt. */
49
+ export function admitRuntimeFormat(serviceDir) {
50
+ const file = join(serviceDir, 'runtime-format.sqlite');
51
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
52
+ const database = new DatabaseSync(toNamespacedPath(file));
53
+ try {
54
+ database.exec('PRAGMA synchronous = FULL; CREATE TABLE IF NOT EXISTS runtime_format (id INTEGER PRIMARY KEY CHECK(id = 1), schema INTEGER NOT NULL); BEGIN IMMEDIATE;');
55
+ const row = database.prepare('SELECT schema FROM runtime_format WHERE id = 1').get();
56
+ if (row && (row.schema < RUNTIME_FORMAT.reads.min || row.schema > RUNTIME_FORMAT.reads.max))
57
+ throw new Error('This runtime cannot read the installed state format.');
58
+ database.prepare('INSERT INTO runtime_format VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET schema = excluded.schema').run(RUNTIME_FORMAT.writes);
59
+ database.exec('COMMIT');
60
+ }
61
+ finally {
62
+ database.close();
63
+ }
64
+ }
65
+ export function observedRuntimeFormats(serviceDir) {
66
+ const database = new DatabaseSync(toNamespacedPath(join(serviceDir, 'runtime-format.sqlite')), { readOnly: true });
67
+ try {
68
+ const row = database.prepare('SELECT schema FROM runtime_format WHERE id = 1').get();
69
+ if (!row || !Number.isSafeInteger(row.schema) || row.schema < 1)
70
+ throw new Error('The installed state format has no valid receipt.');
71
+ return { [RUNTIME_FORMAT.id]: row.schema };
72
+ }
73
+ finally {
74
+ database.close();
75
+ }
76
+ }
77
+ export function installedPackage(root = packageRoot) {
78
+ return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
79
+ }
80
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/updates/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EACL,yBAAyB,GAC1B,MAAM,0BAA0B,CAAC;AAIlC,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,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IACzD,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AACtE,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { Metadata } from '@tufjs/models';
2
+ import { type AcceptedRuntimeRelease } from '@amalgm/core/supervision';
3
+ import { type UpdateStore } from './store.js';
4
+ export declare const RELEASE_ORIGIN = "https://amalgm-desktop-releases.fly.dev";
5
+ export declare function runtimeRoot(value: unknown, lane: string): Metadata<import("@tufjs/models").Root>;
6
+ /** Intentionally matches Electron's pinned host adapter: TUF owns verification;
7
+ * SQLite owns the four metadata writes, including partially failed refreshes.
8
+ * Neither consumer resets trust from a disposable filesystem mirror. */
9
+ export declare class RuntimeTrust {
10
+ readonly store: UpdateStore;
11
+ readonly signal: AbortSignal;
12
+ readonly repository: URL;
13
+ readonly lane: 'main' | 'preview';
14
+ constructor(store: UpdateStore, signal: AbortSignal, origin?: string);
15
+ current(previous?: AcceptedRuntimeRelease): Promise<AcceptedRuntimeRelease>;
16
+ /** A historical signature identifies existing code; only current() authorizes
17
+ * a desired release. Expiry cannot retroactively change the installed bytes. */
18
+ baseline(version: string): Promise<AcceptedRuntimeRelease>;
19
+ private admit;
20
+ }