gestalt-mobile 0.78.2 → 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.
@@ -16,7 +16,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-C6uq_I_x.js"></script>
19
+ <script type="module" crossorigin src="/assets/index-jLy1t3Qp.js"></script>
20
20
  <link rel="stylesheet" crossorigin href="/assets/index-DRiZTklh.css">
21
21
  </head>
22
22
  <body>
@@ -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-'));
@@ -29,6 +29,8 @@ export function registerForgetSession(app, deps) {
29
29
  });
30
30
  if (operation.phase !== 'completed')
31
31
  return reply.code(503).send({ code: 'SESSION_FORGET_FAILED', operation });
32
+ if (operation.scratchRetained && !operation.keepFilesRequested)
33
+ reply.header('x-gestalt-scratch-retained', 'true');
32
34
  return reply.code(204).send();
33
35
  }
34
36
  if (!deps.find(id))
@@ -43,7 +43,7 @@ async function prepareReadOnlyDirectories(root, directories) {
43
43
  }
44
44
  /** Only the managed namespace is traversed. There are no prefix/age/PID legacy recognizers. */
45
45
  export class FilesystemScratchCleanup {
46
- async cleanSession(session, authorized, protectedSessions) {
46
+ async cleanSession(session, authorized, protectedSessions, { retainBorrowed = false } = {}) {
47
47
  // A retained session can outlive its workspace (including Self DEBUG).
48
48
  // Only an absent workspace is already clean; existing links and invalid
49
49
  // paths must still pass the normal canonical-path checks below.
@@ -64,9 +64,20 @@ export class FilesystemScratchCleanup {
64
64
  throw error;
65
65
  }
66
66
  }
67
- const counts = await this.cleanWorkspace(session.workspacePath, protectedSessions, mobileScratchOwnerId(session.id), authorized);
68
- if (counts.skipped || counts.failed)
67
+ const ownerId = mobileScratchOwnerId(session.id);
68
+ const counts = await this.cleanWorkspace(session.workspacePath, protectedSessions, ownerId, authorized);
69
+ const borrowed = counts.leasedMobileSessions;
70
+ if (counts.failed ||
71
+ (counts.skipped && (!retainBorrowed || counts.skipped !== borrowed.length)))
69
72
  throw new Error('SESSION_CLEANUP_FAILED');
73
+ // A missing logical owner cannot prove that its external runtime was retired.
74
+ if (process.getuid &&
75
+ (await hasRuntimeOwner({ workspacePath: session.workspacePath, ownerId }, new Set(borrowed.flatMap(({ runtimeDirectory }) => runtimeDirectory ?? [])))))
76
+ throw new Error('SESSION_CLEANUP_FAILED');
77
+ if (!authorized())
78
+ throw new Error('SESSION_CLEANUP_FAILED');
79
+ if (borrowed.length)
80
+ return 'retained';
70
81
  }
71
82
  async canonicalWorkspace(path) {
72
83
  return canonicalScratchWorkspace(path);
@@ -138,7 +149,7 @@ export class FilesystemScratchCleanup {
138
149
  if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0)) {
139
150
  if (authorized && marker.ownerKind === 'mobile-session') {
140
151
  if (marker.runtime)
141
- await validateRuntime(marker, marker.runtime, true);
152
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
142
153
  counts.leasedMobileSessions.push({
143
154
  sessionId: marker.sessionId,
144
155
  runtimeDirectory: marker.runtime?.directory,
@@ -148,7 +159,8 @@ export class FilesystemScratchCleanup {
148
159
  }
149
160
  if (authorized) {
150
161
  await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
151
- if (marker.runtime && (await validateRuntime(marker, marker.runtime, true)))
162
+ if (marker.runtime &&
163
+ (await validateRuntime(marker, marker.runtime, { allowRetiring: true })))
152
164
  await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
153
165
  }
154
166
  // Manual Clean Tmp bounds opportunistic inspection. Explicit Forget
@@ -157,7 +169,7 @@ export class FilesystemScratchCleanup {
157
169
  const readOnlyDirectories = await this.validatePayload(directory, inspectionBudget());
158
170
  let readOnlyRuntimeDirectories = [];
159
171
  if (marker.runtime) {
160
- const present = await validateRuntime(marker, marker.runtime, true);
172
+ const present = await validateRuntime(marker, marker.runtime, { allowRetiring: true });
161
173
  if (present) {
162
174
  await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
163
175
  (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
@@ -323,7 +335,7 @@ export class FilesystemScratchCleanup {
323
335
  if (!marker.runtime)
324
336
  return;
325
337
  const runtime = marker.runtime;
326
- if (!(await validateRuntime(marker, runtime, true)))
338
+ if (!(await validateRuntime(marker, runtime, { allowRetiring: true })))
327
339
  return;
328
340
  // Persist retirement intent before either authority record is removed.
329
341
  // After a crash an absent runtime is acceptable only with this exact record;
@@ -346,13 +358,13 @@ export class FilesystemScratchCleanup {
346
358
  if (!attributed && children.length)
347
359
  reject('unrecognized');
348
360
  if (attributed) {
349
- await validateRuntime(marker, marker.runtime, true);
361
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
350
362
  await prepareReadOnlyDirectories(runtime.directory, readOnlyDirectories);
351
363
  for (const child of children) {
352
364
  if (child.toString() !== runtimeMarkerName)
353
365
  await rm(payloadPath(runtime.directory, child), { recursive: true });
354
366
  }
355
- await validateRuntime(marker, marker.runtime, true);
367
+ await validateRuntime(marker, marker.runtime, { allowRetiring: true });
356
368
  await rm(join(runtime.directory, runtimeMarkerName));
357
369
  }
358
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 = {
@@ -22,7 +22,9 @@ export class FilesystemWorkspaceForget {
22
22
  const workspace = canonicalSessionWorkspace(session.workspacePath);
23
23
  const others = knownSessions().filter((other) => other.id !== session.id);
24
24
  if (others.some((other) => canonicalSessionWorkspace(other.workspacePath) === workspace))
25
- return 'retained';
25
+ return new FilesystemScratchCleanup().cleanSession(session, authorized, knownSessions, {
26
+ retainBorrowed: true,
27
+ });
26
28
  const temporary = join(workspace, 'tmp');
27
29
  for (const other of others) {
28
30
  if (workspaceContains(temporary, canonicalSessionWorkspace(other.workspacePath)))
@@ -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.2",
3
+ "version": "0.78.4",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",