gestalt-mobile 0.78.3 → 0.78.4

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.
@@ -6,7 +6,7 @@
6
6
  import { once } from 'node:events';
7
7
  import { execFile } from 'node:child_process';
8
8
  import { promisify } from 'node:util';
9
- import { createHash } from 'node:crypto';
9
+ import { createHash, randomUUID } from 'node:crypto';
10
10
  import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
11
11
  import { DatabaseSync } from 'node:sqlite';
12
12
  import { tmpdir } from 'node:os';
@@ -33,6 +33,7 @@ import { exportControlPlaneTrace } from './features/control-plane-trace/export-t
33
33
  import { authorizationSessionId, authorizedDeviceId, localOwnerId, webAuthnCredentialId, } from './features/auth/domain/identifiers.js';
34
34
  import { deviceNickname } from './features/auth/domain/device-nickname.js';
35
35
  import { workspaceId } from './platform/catalog/workspace-id.js';
36
+ import { mobileScratchOwnerId, readMarker, scratchMarkerName, } from './platform/scratch/scratch-filesystem.js';
36
37
  import { FilesystemPlanStatusSource, planStatusDirectoryPath, planStatusFilePath, } from './platform/plans/filesystem-plan-status-source.js';
37
38
  import { toOrgPlanAttentionAcknowledgement, toOrgPlanAttentionToolResponse, } from '../shared/contracts/org-plan-attention.js';
38
39
  import { toOrgPlanCheckpointToolResponse } from '../shared/contracts/org-plan-checkpoint.js';
@@ -8535,6 +8536,101 @@ describe('production composition', () => {
8535
8536
  });
8536
8537
  });
8537
8538
  describeCompositionConcern('sessions', () => {
8539
+ it.skipIf(process.platform !== 'linux')('accepts a prompt on the original thread after a reboot clears its runtime scratch', async () => {
8540
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-reboot-root-'));
8541
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-reboot-state-'));
8542
+ ownTemporaryPaths(root, dataDir);
8543
+ const workspace = join(root, 'workspace');
8544
+ await mkdir(workspace);
8545
+ const handles = [];
8546
+ const app = await composeAuthorizedApp({
8547
+ root,
8548
+ dataDir,
8549
+ relyingParty,
8550
+ installedCodexVersion: 'codex-cli 0.172.0',
8551
+ startAppServers: true,
8552
+ launchAppServer: liveAppServer(handles),
8553
+ profiles: {
8554
+ list: async () => [],
8555
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
8556
+ },
8557
+ });
8558
+ let markerPath;
8559
+ try {
8560
+ const id = await createComposedSession(app);
8561
+ const url = `/api/sessions/${id}`;
8562
+ const { threadId } = await vi.waitFor(async () => {
8563
+ const session = (await app.inject(url)).json();
8564
+ expect(session.state).toBe('ready');
8565
+ return session;
8566
+ });
8567
+ expect((await app.inject({ method: 'POST', url: `${url}/stop` })).statusCode).toBe(202);
8568
+ const owner = join(workspace, 'tmp', 'sessions', mobileScratchOwnerId(id));
8569
+ markerPath = join(owner, scratchMarkerName);
8570
+ const marker = (await readMarker(markerPath));
8571
+ const runtime = marker.runtime;
8572
+ const payload = join(owner, 'retained.txt');
8573
+ await writeFile(payload, 'workspace payload');
8574
+ await rm(runtime.directory, { recursive: true });
8575
+ // Simulate a pre-boot runtime directory using the persisted birth time.
8576
+ const preBoot = new Date('2000-01-01T00:00:00.000Z');
8577
+ const [device, inode] = runtime.identity.split(':');
8578
+ const leaseId = randomUUID();
8579
+ const leasePath = join(owner, 'leases', `${leaseId}.json`);
8580
+ const previousLease = JSON.stringify({
8581
+ schemaVersion: 1,
8582
+ ownerId: marker.ownerId,
8583
+ workspacePath: workspace,
8584
+ leaseId,
8585
+ state: 'active',
8586
+ processIdentity: randomUUID(),
8587
+ createdAt: preBoot.toISOString(),
8588
+ updatedAt: preBoot.toISOString(),
8589
+ consumers: ['runtime-before-reboot'],
8590
+ });
8591
+ await writeFile(leasePath, previousLease, { mode: 0o600 });
8592
+ await writeFile(markerPath, JSON.stringify({
8593
+ ...marker,
8594
+ createdAt: preBoot.toISOString(),
8595
+ runtime: {
8596
+ ...runtime,
8597
+ identity: `${device}:${inode}:${BigInt(preBoot.getTime()) * 1000000n}`,
8598
+ },
8599
+ }));
8600
+ const response = await app.inject({
8601
+ method: 'POST',
8602
+ url: `${url}/turns`,
8603
+ payload: { text: 'fixture' },
8604
+ });
8605
+ expect(response.statusCode, JSON.stringify(response.json().code)).toBe(202);
8606
+ expect(response.json()).toMatchObject({ threadId, state: 'turnActive' });
8607
+ const writer = handles.find((handle) => handle.calls.includes('thread/resume'));
8608
+ expect(writer.requests).toEqual(expect.arrayContaining([
8609
+ expect.objectContaining({
8610
+ method: 'thread/resume',
8611
+ params: expect.objectContaining({ threadId }),
8612
+ }),
8613
+ expect.objectContaining({
8614
+ method: 'turn/start',
8615
+ params: expect.objectContaining({ threadId }),
8616
+ }),
8617
+ ]));
8618
+ expect(handles.flatMap((handle) => handle.calls).filter((method) => method === 'thread/start')).toHaveLength(1);
8619
+ const updated = (await readMarker(markerPath));
8620
+ expect(updated.runtime?.directory).not.toBe(runtime.directory);
8621
+ expect(updated.providerThreads).toEqual(marker.providerThreads);
8622
+ expect(await readFile(payload, 'utf8')).toBe('workspace payload');
8623
+ expect(await readFile(leasePath, 'utf8')).toBe(previousLease);
8624
+ }
8625
+ finally {
8626
+ await app.close();
8627
+ if (markerPath) {
8628
+ const marker = (await readMarker(markerPath));
8629
+ if (marker.runtime)
8630
+ await rm(marker.runtime.directory, { recursive: true, force: true });
8631
+ }
8632
+ }
8633
+ });
8538
8634
  it('redeems one weekly reset credit on a matched terminal Codex failure and records a receipt', async () => {
8539
8635
  const root = await mkdtemp(join(tmpdir(), 'gestalt-weekly-reset-root-'));
8540
8636
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-weekly-reset-state-'));
@@ -149,7 +149,7 @@ export class FilesystemScratchCleanup {
149
149
  if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0)) {
150
150
  if (authorized && marker.ownerKind === 'mobile-session') {
151
151
  if (marker.runtime)
152
- await validateRuntime(marker, marker.runtime, true);
152
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
153
153
  counts.leasedMobileSessions.push({
154
154
  sessionId: marker.sessionId,
155
155
  runtimeDirectory: marker.runtime?.directory,
@@ -159,7 +159,8 @@ export class FilesystemScratchCleanup {
159
159
  }
160
160
  if (authorized) {
161
161
  await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
162
- if (marker.runtime && (await validateRuntime(marker, marker.runtime, true)))
162
+ if (marker.runtime &&
163
+ (await validateRuntime(marker, marker.runtime, { allowRetiring: true })))
163
164
  await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
164
165
  }
165
166
  // Manual Clean Tmp bounds opportunistic inspection. Explicit Forget
@@ -168,7 +169,7 @@ export class FilesystemScratchCleanup {
168
169
  const readOnlyDirectories = await this.validatePayload(directory, inspectionBudget());
169
170
  let readOnlyRuntimeDirectories = [];
170
171
  if (marker.runtime) {
171
- const present = await validateRuntime(marker, marker.runtime, true);
172
+ const present = await validateRuntime(marker, marker.runtime, { allowRetiring: true });
172
173
  if (present) {
173
174
  await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
174
175
  (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
@@ -334,7 +335,7 @@ export class FilesystemScratchCleanup {
334
335
  if (!marker.runtime)
335
336
  return;
336
337
  const runtime = marker.runtime;
337
- if (!(await validateRuntime(marker, runtime, true)))
338
+ if (!(await validateRuntime(marker, runtime, { allowRetiring: true })))
338
339
  return;
339
340
  // Persist retirement intent before either authority record is removed.
340
341
  // After a crash an absent runtime is acceptable only with this exact record;
@@ -357,13 +358,13 @@ export class FilesystemScratchCleanup {
357
358
  if (!attributed && children.length)
358
359
  reject('unrecognized');
359
360
  if (attributed) {
360
- await validateRuntime(marker, marker.runtime, true);
361
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
361
362
  await prepareReadOnlyDirectories(runtime.directory, readOnlyDirectories);
362
363
  for (const child of children) {
363
364
  if (child.toString() !== runtimeMarkerName)
364
365
  await rm(payloadPath(runtime.directory, child), { recursive: true });
365
366
  }
366
- await validateRuntime(marker, marker.runtime, true);
367
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
367
368
  await rm(join(runtime.directory, runtimeMarkerName));
368
369
  }
369
370
  if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
@@ -11,7 +11,8 @@ import { claimOwnerFence } from './owner-fence.js';
11
11
  import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
12
12
  export { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
13
13
  import { withScratchContainment } from './containment-fence.js';
14
- import { allocateRuntime, validateRuntime } from './runtime-root.js';
14
+ import { readManagedScratchLeases } from './managed-scratch-owner.js';
15
+ import { allocateRuntime, linuxBootTime, runtimeMarkerName, validateRuntime, } from './runtime-root.js';
15
16
  function validId(value) {
16
17
  if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(value))
17
18
  throw new Error('SESSION_SCRATCH_INVALID_ID');
@@ -37,6 +38,60 @@ function validateMarker(value, expected) {
37
38
  throw new Error('SESSION_SCRATCH_MARKER_MISMATCH');
38
39
  return marker;
39
40
  }
41
+ async function publishOwnerMarker(directory, marker) {
42
+ const staging = join(directory, `.owner-${randomUUID()}.json`);
43
+ const handle = await open(staging, 'wx', 0o600);
44
+ try {
45
+ try {
46
+ await handle.writeFile(`${JSON.stringify(marker)}\n`);
47
+ await handle.sync();
48
+ }
49
+ finally {
50
+ await handle.close();
51
+ }
52
+ await privateDirectory(directory, false);
53
+ await rename(staging, join(directory, scratchMarkerName));
54
+ }
55
+ catch (error) {
56
+ await unlink(staging).catch(() => undefined);
57
+ throw error;
58
+ }
59
+ }
60
+ /** A legacy Mobile owner can survive a Linux reboot that clears its runtime in /tmp. */
61
+ async function recoverMissingMobileRuntime(directory, marker) {
62
+ const runtime = marker.runtime;
63
+ if (await validateRuntime(marker, runtime, { allowMissing: true }))
64
+ return;
65
+ const boot = await linuxBootTime();
66
+ const birth = BigInt(runtime.identity.split(':')[2]);
67
+ const missing = new Error('SESSION_SCRATCH_RUNTIME_MISSING');
68
+ if (boot === undefined ||
69
+ birth === 0n ||
70
+ birth >= BigInt(boot) * 1000000n ||
71
+ Date.parse(marker.createdAt) >= boot)
72
+ throw missing;
73
+ const leases = await readManagedScratchLeases(directory, marker);
74
+ if (leases.some((lease) => lease.state === 'active' &&
75
+ (Date.parse(lease.createdAt) >= boot || Date.parse(lease.updatedAt) >= boot)))
76
+ throw missing;
77
+ // Publish under the existing workspace and owner fences. Keep old lease
78
+ // records protective and replace only the locator for the missing runtime.
79
+ const replacement = await allocateRuntime(marker);
80
+ try {
81
+ await publishOwnerMarker(directory, { ...marker, runtime: replacement });
82
+ }
83
+ catch (error) {
84
+ // This allocation was never handed to a borrower. Only remove its own
85
+ // locator and empty directory if identity and ownership still agree.
86
+ await (async () => {
87
+ await validateRuntime(marker, replacement);
88
+ await unlink(join(replacement.directory, runtimeMarkerName));
89
+ await rmdir(replacement.directory);
90
+ })().catch(() => undefined);
91
+ throw error;
92
+ }
93
+ marker.runtime = replacement;
94
+ }
40
95
  export class FilesystemSessionScratch {
41
96
  assertAvailable;
42
97
  reserveRuntime;
@@ -244,22 +299,7 @@ export class FilesystemSessionScratch {
244
299
  if (marker.providerThreads.some((thread) => thread.provider === provider && thread.threadId === threadId))
245
300
  return;
246
301
  marker.providerThreads.push({ provider, threadId });
247
- const staging = join(context.directory, `.owner-${randomUUID()}.json`);
248
- const handle = await open(staging, 'wx', 0o600);
249
- try {
250
- await handle.writeFile(`${JSON.stringify(marker)}\n`);
251
- await handle.sync();
252
- await handle.close();
253
- await privateDirectory(context.directory, false);
254
- await rename(staging, join(context.directory, scratchMarkerName));
255
- }
256
- finally {
257
- await handle.close();
258
- await unlink(staging).catch((error) => {
259
- if (error.code !== 'ENOENT')
260
- throw error;
261
- });
262
- }
302
+ await publishOwnerMarker(context.directory, marker);
263
303
  }
264
304
  finally {
265
305
  await releaseFence();
@@ -347,8 +387,12 @@ export class FilesystemSessionScratch {
347
387
  else {
348
388
  marker = validateMarker(await readMarker(markerPath), expected);
349
389
  }
350
- if (marker.schemaVersion === 2)
351
- await validateRuntime(marker, marker.runtime);
390
+ if (marker.schemaVersion === 2) {
391
+ if (!created && marker.ownerKind === 'mobile-session')
392
+ await recoverMissingMobileRuntime(directory, marker);
393
+ else
394
+ await validateRuntime(marker, marker.runtime);
395
+ }
352
396
  await privateDirectory(directory, false);
353
397
  const runtimeDirectory = marker.runtime?.directory ?? directory;
354
398
  const context = {
@@ -100,7 +100,7 @@ export async function readManagedScratchAttribution(directory, allowRetired = fa
100
100
  await privateDirectory(directory, false);
101
101
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
102
102
  if (marker.runtime)
103
- await validateRuntime(marker, marker.runtime, allowRetired);
103
+ await validateRuntime(marker, marker.runtime, { allowRetiring: allowRetired });
104
104
  return { directory, workspacePath, ownerId, marker };
105
105
  }
106
106
  /** A runtime locator is not authority until the durable owner binds it back. */
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { randomBytes } from 'node:crypto';
7
- import { lstat, mkdir, open, readdir, realpath } from 'node:fs/promises';
7
+ import { lstat, mkdir, open, readFile, readdir, realpath } from 'node:fs/promises';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { privateDirectory, readMarker } from './scratch-filesystem.js';
10
10
  export const runtimeMarkerName = '.gestalt-runtime.json';
@@ -67,7 +67,7 @@ export async function allocateRuntime(owner) {
67
67
  throw new Error('SESSION_SCRATCH_RUNTIME_COLLISION');
68
68
  }
69
69
  /** The workspace record and physical root must agree, including inode identity. */
70
- export async function validateRuntime(owner, runtime, allowRetiring = false) {
70
+ export async function validateRuntime(owner, runtime, { allowRetiring = false, allowMissing = false, } = {}) {
71
71
  const container = await runtimeContainer();
72
72
  if (!runtime ||
73
73
  typeof runtime.directory !== 'string' ||
@@ -80,15 +80,20 @@ export async function validateRuntime(owner, runtime, allowRetiring = false) {
80
80
  !/^\d+:\d+:\d+$/.test(runtime.identity) ||
81
81
  (runtime.retiring !== undefined && (runtime.retiring !== true || !allowRetiring)))
82
82
  reject();
83
- await privateDirectory(container, false);
83
+ try {
84
+ await privateDirectory(container, false);
85
+ }
86
+ catch (error) {
87
+ if (allowMissing && error.code === 'ENOENT')
88
+ return false;
89
+ throw error;
90
+ }
84
91
  try {
85
92
  if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
86
93
  reject();
87
94
  }
88
95
  catch (error) {
89
- // This flag belongs only to attribution/cleanup. Actual retirement still
90
- // requires the authoritative roster, released leases and both owner fences.
91
- if (allowRetiring && error.code === 'ENOENT')
96
+ if ((allowMissing || allowRetiring) && error.code === 'ENOENT')
92
97
  return false;
93
98
  throw error;
94
99
  }
@@ -105,6 +110,17 @@ export async function validateRuntime(owner, runtime, allowRetiring = false) {
105
110
  reject();
106
111
  return true;
107
112
  }
113
+ /** Only Linux supplies the boot-time evidence used to recover old Mobile bindings. */
114
+ export async function linuxBootTime() {
115
+ if (process.platform !== 'linux')
116
+ return undefined;
117
+ const stat = await readFile('/proc/stat', 'utf8').catch(() => '');
118
+ const seconds = /^btime (\d+)$/m.exec(stat)?.[1];
119
+ const time = Number(seconds) * 1000;
120
+ if (Number.isSafeInteger(time) && time > 0 && time <= Date.now())
121
+ return time;
122
+ return undefined;
123
+ }
108
124
  /** A missing workspace does not authorize abandoning an external payload root. */
109
125
  export async function hasRuntimeOwner(owner, retainedDirectories) {
110
126
  const container = await runtimeContainer();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.78.3",
3
+ "version": "0.78.4",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",