gestalt-mobile 0.71.5 → 0.72.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 (47) hide show
  1. package/README.md +15 -48
  2. package/dist/client/assets/index-CwgSPgbi.css +1 -0
  3. package/dist/client/assets/index-ME1MRi_3.js +182 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/client/features/chat/activity-summary.js +11 -0
  6. package/dist/server/client/features/chat/chat-projection.js +6 -2
  7. package/dist/server/server/cli.js +0 -3
  8. package/dist/server/server/composition.contracts.js +0 -2
  9. package/dist/server/server/composition.js +8 -25
  10. package/dist/server/server/config.js +2 -5
  11. package/dist/server/server/features/agent-activity/registry.js +42 -15
  12. package/dist/server/server/features/catalog/get-bootstrap/use-case.js +0 -1
  13. package/dist/server/server/features/catalog/register-routes.js +0 -3
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +6 -0
  15. package/dist/server/server/features/skills/list-available/endpoint.js +1 -1
  16. package/dist/server/server/features/skills/model/skill-profile.js +2 -3
  17. package/dist/server/server/platform/codex/capability-deadline.js +26 -0
  18. package/dist/server/server/platform/codex/codex-capabilities.js +23 -56
  19. package/dist/server/server/platform/codex/codex-playwright.js +3 -3
  20. package/dist/server/server/platform/codex/codex-serena.js +1 -1
  21. package/dist/server/server/platform/codex/mcp-startup-failure.js +0 -25
  22. package/dist/server/server/platform/codex/normalizer.js +0 -17
  23. package/dist/server/server/platform/codex/retired-capability-migration.js +105 -0
  24. package/dist/server/server/platform/codex/session-runtime.js +4 -52
  25. package/dist/server/server/platform/codex/startup-guidance.fixture.js +3 -3
  26. package/dist/server/server/platform/kimi/kimi-skill-catalog.js +2 -8
  27. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -7
  28. package/dist/server/server/platform/scratch/containment-fence.js +76 -20
  29. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +139 -13
  30. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +20 -11
  31. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +64 -8
  32. package/dist/server/server/platform/scratch/managed-scratch-owner.js +17 -1
  33. package/dist/server/server/platform/scratch/runtime-root.js +147 -0
  34. package/dist/server/server/platform/scratch/workspace-publication.js +67 -0
  35. package/dist/server/server/platform/skills/codex-skill-catalog.js +9 -7
  36. package/dist/server/shared/contracts/mcp-startup-failure.js +5 -30
  37. package/package.json +1 -1
  38. package/dist/client/assets/index-BOJci8Jh.css +0 -1
  39. package/dist/client/assets/index-Cb4qCgbe.js +0 -183
  40. package/dist/server/server/features/catalog/get-xerj-status/endpoint.js +0 -13
  41. package/dist/server/server/platform/retrieval/codex-xerj.js +0 -205
  42. package/dist/server/server/platform/retrieval/managed-xerj.js +0 -196
  43. package/dist/server/server/platform/retrieval/xerj-index-config.js +0 -70
  44. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +0 -124
  45. package/dist/server/server/platform/retrieval/xerj-indexer.js +0 -399
  46. package/dist/server/shared/contracts/xerj-startup.js +0 -76
  47. /package/dist/server/{shared/contracts/xerj-status.js → server/platform/codex/capability-contracts.js} +0 -0
@@ -4,14 +4,16 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
- import { lstat, mkdir, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
7
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
8
8
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { emptyScratchCounts, } from '../../features/sessions/clean-tmp/use-case.js';
10
10
  import { mobileScratchOwnerId, privateDirectory, scratchMarkerName } from './scratch-filesystem.js';
11
11
  import { claimOwnerFence } from './owner-fence.js';
12
12
  import { isAmbiguousLegacyScratch } from './legacy-scratch-layouts.js';
13
13
  import { canonicalScratchWorkspace, managedScratchOwnerId, readManagedScratchOwner, readManagedScratchLeases, } from './managed-scratch-owner.js';
14
- import { claimScratchContainment, containmentFenceName } from './containment-fence.js';
14
+ import { claimScratchContainment, containmentFenceName, } from './containment-fence.js';
15
+ import { workspacePublicationName } from './workspace-publication.js';
16
+ import { hasRuntimeOwner, runtimeIdentity, runtimeMarkerName, validateRuntime, } from './runtime-root.js';
15
17
  function reject(reason) {
16
18
  throw new Error(`SCRATCH_CLEANUP_${reason}`);
17
19
  }
@@ -30,8 +32,15 @@ export class FilesystemScratchCleanup {
30
32
  await lstat(session.workspacePath);
31
33
  }
32
34
  catch (error) {
33
- if (error.code === 'ENOENT')
35
+ if (error.code === 'ENOENT') {
36
+ if (process.getuid &&
37
+ (await hasRuntimeOwner({
38
+ workspacePath: session.workspacePath,
39
+ ownerId: mobileScratchOwnerId(session.id),
40
+ })))
41
+ throw new Error('SESSION_CLEANUP_FAILED');
34
42
  return;
43
+ }
35
44
  throw error;
36
45
  }
37
46
  }
@@ -42,7 +51,7 @@ export class FilesystemScratchCleanup {
42
51
  async canonicalWorkspace(path) {
43
52
  return canonicalScratchWorkspace(path);
44
53
  }
45
- async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized) {
54
+ async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized, authorizedSessionId, inherited) {
46
55
  await this.canonicalWorkspace(workspacePath);
47
56
  const counts = emptyScratchCounts();
48
57
  const temporary = join(workspacePath, 'tmp');
@@ -94,12 +103,26 @@ export class FilesystemScratchCleanup {
94
103
  // A removal reservation/partial allocation is not an owner yet. Inspect
95
104
  // its locator before claiming a fence; authority is rechecked below.
96
105
  await readManagedScratchOwner(directory, workspacePath, ownerId);
97
- containment = await claimScratchContainment(directory, ownerId);
106
+ containment = await claimScratchContainment(directory, ownerId, inherited);
98
107
  release = await claimOwnerFence(directory);
99
108
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
100
109
  await this.releasedLeases(directory, marker);
101
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
110
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
111
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
112
+ if (authorized) {
113
+ await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
114
+ if (marker.runtime && (await validateRuntime(marker, marker.runtime, true)))
115
+ await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
116
+ }
102
117
  await this.validatePayload(directory);
118
+ if (marker.runtime) {
119
+ const present = await validateRuntime(marker, marker.runtime, true);
120
+ if (present) {
121
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
122
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
123
+ await this.validatePayload(marker.runtime.directory);
124
+ }
125
+ }
103
126
  await privateDirectory(directory, false);
104
127
  await containment.revalidate();
105
128
  if (name === ownerId) {
@@ -107,7 +130,8 @@ export class FilesystemScratchCleanup {
107
130
  // Reserve the random destination exclusively; never replace a collision.
108
131
  await mkdir(retired, { mode: 0o700 });
109
132
  try {
110
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
133
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
134
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
111
135
  }
112
136
  catch (error) {
113
137
  await rmdir(retired);
@@ -122,7 +146,8 @@ export class FilesystemScratchCleanup {
122
146
  }
123
147
  await privateDirectory(directory, false);
124
148
  await containment.revalidate();
125
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
149
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
150
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
126
151
  // Keep authority metadata until disposable payload has been removed. A failed
127
152
  // payload deletion is retryable; an interrupted metadata retirement is unknown.
128
153
  for (const child of await readdir(directory, { encoding: 'buffer' })) {
@@ -130,6 +155,7 @@ export class FilesystemScratchCleanup {
130
155
  continue;
131
156
  await rm(payloadPath(directory, child), { recursive: true });
132
157
  }
158
+ await this.retireRuntime(directory, marker);
133
159
  if ((await readdir(directory)).includes('leases'))
134
160
  await rm(join(directory, 'leases'), { recursive: true });
135
161
  await rm(join(directory, scratchMarkerName));
@@ -202,7 +228,96 @@ export class FilesystemScratchCleanup {
202
228
  if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0))
203
229
  reject('lease');
204
230
  }
205
- async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized) {
231
+ /** Final workspace authority can retire positively attributed nested namespaces,
232
+ * but every nested roster, lease, inode and fence still has to pass its gate. */
233
+ async retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, inherited, skipContainer = false, depth = 0, budget = { entries: 0 }) {
234
+ if (depth > 128 || !authorized())
235
+ reject('protected');
236
+ let entries;
237
+ try {
238
+ entries = await readdir(directory, { encoding: 'buffer', withFileTypes: true });
239
+ }
240
+ catch (error) {
241
+ if (error.code === 'ENOENT')
242
+ return;
243
+ throw error;
244
+ }
245
+ for (const entry of entries) {
246
+ if (++budget.entries > 100000)
247
+ reject('unrecognized');
248
+ const name = entry.name.toString();
249
+ if (skipContainer && name === 'sessions')
250
+ continue;
251
+ const path = payloadPath(directory, entry.name), info = await lstat(path);
252
+ if (process.getuid && info.uid !== process.getuid())
253
+ reject('unsafe');
254
+ if (!info.isDirectory() || info.isSymbolicLink())
255
+ continue;
256
+ if (name === 'tmp') {
257
+ const workspace = directory.toString();
258
+ if (Buffer.isBuffer(directory) && !Buffer.from(workspace).equals(directory))
259
+ reject('unrecognized');
260
+ const counts = await this.cleanWorkspace(workspace, protectedSessions, undefined, authorized, authorizedSessionId, inherited);
261
+ if (counts.skipped || counts.failed)
262
+ reject('unrecognized');
263
+ const container = join(workspace, 'tmp', 'sessions');
264
+ try {
265
+ await privateDirectory(container, false);
266
+ const remaining = await readdir(container);
267
+ if (remaining.some((child) => child !== '.gitignore'))
268
+ reject('unrecognized');
269
+ if (remaining.includes('.gitignore'))
270
+ await rm(join(container, '.gitignore'));
271
+ await rmdir(container);
272
+ }
273
+ catch (error) {
274
+ if (error.code !== 'ENOENT')
275
+ throw error;
276
+ }
277
+ }
278
+ await this.retireNestedNamespaces(path, protectedSessions, authorized, authorizedSessionId, inherited, name === 'tmp', depth + 1, budget);
279
+ }
280
+ }
281
+ async retireRuntime(directory, marker) {
282
+ if (!marker.runtime)
283
+ return;
284
+ const runtime = marker.runtime;
285
+ if (!(await validateRuntime(marker, runtime, true)))
286
+ return;
287
+ // Persist retirement intent before either authority record is removed.
288
+ // After a crash an absent runtime is acceptable only with this exact record;
289
+ // a replacement inode or a nonempty directory without its marker is retained.
290
+ if (!runtime.retiring) {
291
+ marker.runtime = { ...runtime, retiring: true };
292
+ const staging = join(directory, `.owner-${randomUUID()}.json`);
293
+ const handle = await open(staging, 'wx', 0o600);
294
+ try {
295
+ await handle.writeFile(`${JSON.stringify(marker)}\n`);
296
+ await handle.sync();
297
+ }
298
+ finally {
299
+ await handle.close();
300
+ }
301
+ await rename(staging, join(directory, scratchMarkerName));
302
+ }
303
+ const children = await readdir(runtime.directory, { encoding: 'buffer' });
304
+ const attributed = children.some((child) => child.toString() === runtimeMarkerName);
305
+ if (!attributed && children.length)
306
+ reject('unrecognized');
307
+ if (attributed) {
308
+ await validateRuntime(marker, marker.runtime, true);
309
+ for (const child of children) {
310
+ if (child.toString() !== runtimeMarkerName)
311
+ await rm(payloadPath(runtime.directory, child), { recursive: true });
312
+ }
313
+ await validateRuntime(marker, marker.runtime, true);
314
+ await rm(join(runtime.directory, runtimeMarkerName));
315
+ }
316
+ if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
317
+ reject('unsafe');
318
+ await rmdir(runtime.directory);
319
+ }
320
+ async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized, authorizedOwnerId) {
206
321
  if (authorized && !authorized())
207
322
  reject('protected');
208
323
  const within = (root, path) => {
@@ -211,7 +326,10 @@ export class FilesystemScratchCleanup {
211
326
  };
212
327
  for (const session of protectedSessions()) {
213
328
  // Only this exact targeted owner's authorized Forget may exclude itself.
214
- if (authorized && marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
329
+ if (authorized &&
330
+ marker.ownerId === authorizedOwnerId &&
331
+ marker.ownerKind === 'mobile-session' &&
332
+ session.id === marker.sessionId)
215
333
  continue;
216
334
  if (marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
217
335
  reject('protected');
@@ -227,7 +345,7 @@ export class FilesystemScratchCleanup {
227
345
  }
228
346
  for (const workspace of paths) {
229
347
  const scratch = join(workspace, 'tmp', 'sessions', mobileScratchOwnerId(session.id));
230
- if ([directory, logicalDirectory].some((owner) => within(owner, workspace) || within(owner, scratch)))
348
+ if ([directory, logicalDirectory, ...(marker.runtime ? [marker.runtime.directory] : [])].some((owner) => within(owner, workspace) || within(owner, scratch)))
231
349
  reject('protected');
232
350
  }
233
351
  }
@@ -243,15 +361,23 @@ export class FilesystemScratchCleanup {
243
361
  reject('unrecognized');
244
362
  for (const entry of await readdir(directory, { encoding: 'buffer', withFileTypes: true })) {
245
363
  const child = entry.name;
364
+ if (child.toString() === workspacePublicationName)
365
+ reject('busy');
246
366
  if (++budget.entries > 100_000)
247
367
  reject('unrecognized');
248
368
  if (directory !== root &&
249
- [scratchMarkerName, '.controller-lock', '.association-lock', containmentFenceName].includes(child.toString()))
369
+ [
370
+ scratchMarkerName,
371
+ runtimeMarkerName,
372
+ '.controller-lock',
373
+ '.association-lock',
374
+ containmentFenceName,
375
+ ].includes(child.toString()))
250
376
  reject('unrecognized');
251
377
  const path = payloadPath(directory, child);
252
378
  const info = await lstat(path);
253
379
  if ((process.getuid && info.uid !== process.getuid()) ||
254
- (!info.isDirectory() && !info.isFile() && !info.isSymbolicLink()) ||
380
+ (!info.isDirectory() && !info.isFile() && !info.isSymbolicLink() && !info.isSocket()) ||
255
381
  (info.isFile() && info.nlink !== 1))
256
382
  reject('unsafe');
257
383
  // Payload symlinks (for example npm's .bin entries) are disposable links.
@@ -11,6 +11,7 @@ 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
15
  function validId(value) {
15
16
  if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(value))
16
17
  throw new Error('SESSION_SCRATCH_INVALID_ID');
@@ -18,7 +19,9 @@ function validId(value) {
18
19
  function validateMarker(value, expected) {
19
20
  const marker = value;
20
21
  if (!marker ||
21
- marker.schemaVersion !== 1 ||
22
+ ![1, 2].includes(marker.schemaVersion) ||
23
+ (marker.schemaVersion === 1 && marker.runtime !== undefined) ||
24
+ (marker.schemaVersion === 2 && !marker.runtime) ||
22
25
  marker.ownerKind !== expected.ownerKind ||
23
26
  marker.ownerId !== expected.ownerId ||
24
27
  marker.workspacePath !== expected.workspacePath ||
@@ -46,7 +49,7 @@ export class FilesystemSessionScratch {
46
49
  async borrow(session) {
47
50
  validId(session.id);
48
51
  this.assertAvailable(session.id);
49
- return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
52
+ return this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
50
53
  this.assertAvailable(session.id);
51
54
  const { context, releaseFence } = await this.prepare(session);
52
55
  try {
@@ -120,7 +123,7 @@ export class FilesystemSessionScratch {
120
123
  /** One lease per owned service process, independent of its first caller. */
121
124
  async allocateService(workspacePath, consumer) {
122
125
  validId(consumer);
123
- return withScratchContainment(workspacePath, async () => {
126
+ return this.serialized(workspacePath, () => withScratchContainment(workspacePath, async () => {
124
127
  const leaseId = randomUUID();
125
128
  const ownerId = `service-${randomUUID()}`;
126
129
  const { context, releaseFence } = await this.prepare({ id: ownerId, workspacePath }, leaseId);
@@ -191,7 +194,7 @@ export class FilesystemSessionScratch {
191
194
  released = true;
192
195
  },
193
196
  };
194
- });
197
+ }));
195
198
  }
196
199
  async serialized(key, operation) {
197
200
  const previous = this.pending.get(key);
@@ -208,7 +211,7 @@ export class FilesystemSessionScratch {
208
211
  async allocate(session) {
209
212
  validId(session.id);
210
213
  this.assertAvailable(session.id);
211
- return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
214
+ return this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
212
215
  this.assertAvailable(session.id);
213
216
  const { context, releaseFence } = await this.prepare(session);
214
217
  try {
@@ -226,7 +229,7 @@ export class FilesystemSessionScratch {
226
229
  validId(threadId);
227
230
  if (!['codex', 'kimi'].includes(provider))
228
231
  throw new Error('SESSION_SCRATCH_INVALID_PROVIDER');
229
- await this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
232
+ await this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
230
233
  this.assertAvailable(session.id);
231
234
  const { context, marker, releaseFence } = await this.prepare(session);
232
235
  try {
@@ -301,7 +304,7 @@ export class FilesystemSessionScratch {
301
304
  try {
302
305
  const markerPath = join(directory, scratchMarkerName);
303
306
  const expected = {
304
- schemaVersion: 1,
307
+ schemaVersion: process.platform === 'win32' ? 1 : 2,
305
308
  ownerKind: leaseId ? 'workspace-service' : 'mobile-session',
306
309
  ownerId,
307
310
  workspacePath,
@@ -315,6 +318,8 @@ export class FilesystemSessionScratch {
315
318
  let marker;
316
319
  if (created) {
317
320
  try {
321
+ if (expected.schemaVersion === 2)
322
+ expected.runtime = await allocateRuntime(expected);
318
323
  const handle = await open(markerPath, 'wx', 0o600);
319
324
  try {
320
325
  await handle.writeFile(`${JSON.stringify(expected)}\n`);
@@ -334,21 +339,25 @@ export class FilesystemSessionScratch {
334
339
  else {
335
340
  marker = validateMarker(await readMarker(markerPath), expected);
336
341
  }
342
+ if (marker.schemaVersion === 2)
343
+ await validateRuntime(marker, marker.runtime);
337
344
  await privateDirectory(directory, false);
345
+ const runtimeDirectory = marker.runtime?.directory ?? directory;
338
346
  const context = {
339
347
  workspacePath,
340
348
  ownerId,
341
349
  directory,
342
350
  environment: {
343
- TMPDIR: directory,
344
- TMP: directory,
345
- TEMP: directory,
351
+ TMPDIR: runtimeDirectory,
352
+ TMP: runtimeDirectory,
353
+ TEMP: runtimeDirectory,
346
354
  [scratchContextVariable]: JSON.stringify({
347
- schemaVersion: 1,
355
+ schemaVersion: marker.schemaVersion,
348
356
  workspacePath,
349
357
  ownerId,
350
358
  directory,
351
359
  markerPath,
360
+ ...(marker.runtime ? { runtime: marker.runtime } : {}),
352
361
  }),
353
362
  },
354
363
  };
@@ -4,10 +4,13 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { lstatSync, mkdirSync, realpathSync, renameSync } from 'node:fs';
7
- import { lstat, rm } from 'node:fs/promises';
7
+ import { lstat, readdir, rm } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
9
9
  import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
10
10
  import { canonicalSessionWorkspace, workspaceContains, } from '../persistence/sqlite-workspace-lifecycle.js';
11
+ import { FilesystemScratchCleanup } from './filesystem-scratch-cleanup.js';
12
+ import { claimWorkspacePublication } from './workspace-publication.js';
13
+ import { hasRuntimeOwner } from './runtime-root.js';
11
14
  /** Final Forget owns the entire selected workspace's explicitly disposable tmp directory. */
12
15
  export class FilesystemWorkspaceForget {
13
16
  db;
@@ -24,20 +27,73 @@ export class FilesystemWorkspaceForget {
24
27
  if (workspaceContains(temporary, canonicalSessionWorkspace(other.workspacePath)))
25
28
  throw new WorkspaceSessionConflict('SESSION_NESTED_WORKSPACE', other.id);
26
29
  }
27
- const retired = this.retire(session, operationId, workspace, temporary, authorized);
28
- if (retired)
29
- await rm(retired, { recursive: true, force: true, maxRetries: 3 });
30
- // A non-cooperating external publisher must not turn retained files into a
31
- // successful final Forget. New Mobile starts remain durably fenced.
32
30
  try {
33
- await lstat(temporary);
31
+ await lstat(workspace);
32
+ }
33
+ catch (error) {
34
+ if (error.code !== 'ENOENT')
35
+ throw error;
36
+ await new FilesystemScratchCleanup().cleanSession(session, authorized, knownSessions);
37
+ return;
38
+ }
39
+ // Keep the physical publication fence through durable finalization. It is
40
+ // outside tmp, so a retiring namespace cannot hide it from new publishers.
41
+ const release = await claimWorkspacePublication(workspace);
42
+ try {
43
+ const cleanup = new FilesystemScratchCleanup();
44
+ await cleanup.retireNestedNamespaces(temporary, knownSessions, authorized, session.id, undefined, true);
45
+ const counts = await cleanup.cleanWorkspace(workspace, knownSessions, undefined, authorized, session.id);
46
+ if (counts.skipped || counts.failed)
47
+ throw new Error('SESSION_CLEANUP_FAILED');
48
+ if (process.getuid && (await hasRuntimeOwner({ workspacePath: workspace })))
49
+ throw new Error('SESSION_CLEANUP_FAILED');
50
+ const retired = this.retire(session, operationId, workspace, temporary, authorized);
51
+ if (retired) {
52
+ await this.assertRetired(retired);
53
+ await rm(retired, { recursive: true, force: true, maxRetries: 3 });
54
+ }
55
+ // A non-cooperating external publisher must not turn retained files into a
56
+ // successful final Forget. New Mobile starts remain durably fenced.
57
+ try {
58
+ await lstat(temporary);
59
+ }
60
+ catch (error) {
61
+ if (error.code === 'ENOENT')
62
+ return { release };
63
+ throw error;
64
+ }
65
+ throw new Error('SESSION_CLEANUP_FAILED');
66
+ }
67
+ catch (error) {
68
+ await release();
69
+ throw error;
70
+ }
71
+ }
72
+ async assertRetired(directory, depth = 0, budget = { entries: 0 }) {
73
+ if (depth > 128)
74
+ throw new Error('SESSION_CLEANUP_FAILED');
75
+ let entries;
76
+ try {
77
+ entries = await readdir(directory, { encoding: 'buffer', withFileTypes: true });
34
78
  }
35
79
  catch (error) {
36
80
  if (error.code === 'ENOENT')
37
81
  return;
38
82
  throw error;
39
83
  }
40
- throw new Error('SESSION_CLEANUP_FAILED');
84
+ for (const entry of entries) {
85
+ if (++budget.entries > 100000 ||
86
+ [
87
+ '.gestalt-owner.json',
88
+ '.gestalt-runtime.json',
89
+ '.controller-lock',
90
+ '.containment-lock',
91
+ '.gestalt-scratch-lock',
92
+ ].includes(entry.name.toString()))
93
+ throw new Error('SESSION_CLEANUP_FAILED');
94
+ if (entry.isDirectory() && !entry.isSymbolicLink())
95
+ await this.assertRetired(Buffer.concat([Buffer.from(directory), Buffer.from('/'), entry.name]), depth + 1, budget);
96
+ }
41
97
  }
42
98
  retire(session, operationId, workspace, temporary, authorized) {
43
99
  // The short synchronous transaction atomically checks authority and moves
@@ -6,6 +6,7 @@
6
6
  import { lstat, readdir, realpath } from 'node:fs/promises';
7
7
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
8
8
  import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, } from './scratch-filesystem.js';
9
+ import { runtimeMarkerName, validateRuntime } from './runtime-root.js';
9
10
  export const scratchUuidPattern = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
10
11
  const ownerPattern = `(?:mobile-[0-9a-f]{64}|(?:cli|service)-${scratchUuidPattern})`;
11
12
  const ownerName = new RegExp(`^${ownerPattern}$`);
@@ -44,7 +45,9 @@ export async function readManagedScratchOwner(directory, workspacePath, ownerId)
44
45
  throw error;
45
46
  }
46
47
  if (!marker ||
47
- marker.schemaVersion !== 1 ||
48
+ ![1, 2].includes(marker.schemaVersion) ||
49
+ (marker.schemaVersion === 1 && marker.runtime !== undefined) ||
50
+ (marker.schemaVersion === 2 && !marker.runtime) ||
48
51
  marker.ownerId !== ownerId ||
49
52
  marker.workspacePath !== workspacePath ||
50
53
  !validTime(marker.createdAt) ||
@@ -96,8 +99,21 @@ export async function readManagedScratchAttribution(directory, allowRetired = fa
96
99
  await privateDirectory(container, false);
97
100
  await privateDirectory(directory, false);
98
101
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
102
+ if (marker.runtime)
103
+ await validateRuntime(marker, marker.runtime, allowRetired);
99
104
  return { directory, workspacePath, ownerId, marker };
100
105
  }
106
+ /** A runtime locator is not authority until the durable owner binds it back. */
107
+ export async function readRuntimeScratchAttribution(runtimeDirectory) {
108
+ await privateDirectory(runtimeDirectory, false);
109
+ const locator = (await readMarker(join(runtimeDirectory, runtimeMarkerName)));
110
+ if (!locator || !isAbsolute(locator.workspacePath) || !ownerName.test(locator.ownerId))
111
+ rejectOwner();
112
+ const owner = await readManagedScratchAttribution(join(locator.workspacePath, 'tmp', 'sessions', locator.ownerId));
113
+ if (owner.marker.runtime?.directory !== runtimeDirectory)
114
+ rejectOwner();
115
+ return owner;
116
+ }
101
117
  function rejectLease() {
102
118
  throw new Error('SESSION_SCRATCH_LEASE_INVALID');
103
119
  }
@@ -0,0 +1,147 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { randomBytes } from 'node:crypto';
7
+ import { lstat, mkdir, open, readdir, realpath } from 'node:fs/promises';
8
+ import { dirname, join } from 'node:path';
9
+ import { privateDirectory, readMarker } from './scratch-filesystem.js';
10
+ export const runtimeMarkerName = '.gestalt-runtime.json';
11
+ export const runtimeRootMaxBytes = 48;
12
+ function reject() {
13
+ throw new Error('SESSION_SCRATCH_RUNTIME_INVALID');
14
+ }
15
+ export async function runtimeContainer() {
16
+ if (!process.getuid)
17
+ reject();
18
+ // /tmp is deliberately independent of TMPDIR and workspace depth. On macOS
19
+ // resolve its system alias once; payload directories themselves are not links.
20
+ return join(await realpath('/tmp'), `gs-${process.getuid()}`);
21
+ }
22
+ export async function runtimeIdentity(directory) {
23
+ await privateDirectory(directory, false);
24
+ const info = await lstat(directory, { bigint: true });
25
+ return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
26
+ }
27
+ export function runtimeRecord(owner, runtime) {
28
+ return {
29
+ schemaVersion: 2,
30
+ ownerId: owner.ownerId,
31
+ workspacePath: owner.workspacePath,
32
+ token: runtime.token,
33
+ identity: runtime.identity,
34
+ };
35
+ }
36
+ /** Only a fresh exclusive directory may become a runtime allocation. */
37
+ export async function allocateRuntime(owner) {
38
+ const container = await runtimeContainer();
39
+ await privateDirectory(container, true);
40
+ for (let attempt = 0; attempt < 16; attempt++) {
41
+ const directory = join(container, randomBytes(10).toString('hex'));
42
+ if (Buffer.byteLength(directory) > runtimeRootMaxBytes)
43
+ throw new Error('SESSION_SCRATCH_RUNTIME_ROOT_TOO_LONG');
44
+ try {
45
+ await mkdir(directory, { mode: 0o700 });
46
+ }
47
+ catch (error) {
48
+ if (error.code === 'EEXIST')
49
+ continue;
50
+ throw error;
51
+ }
52
+ const runtime = {
53
+ directory,
54
+ token: randomBytes(32).toString('hex'),
55
+ identity: await runtimeIdentity(directory),
56
+ };
57
+ const handle = await open(join(directory, runtimeMarkerName), 'wx', 0o600);
58
+ try {
59
+ await handle.writeFile(`${JSON.stringify(runtimeRecord(owner, runtime))}\n`);
60
+ await handle.sync();
61
+ }
62
+ finally {
63
+ await handle.close();
64
+ }
65
+ return runtime;
66
+ }
67
+ throw new Error('SESSION_SCRATCH_RUNTIME_COLLISION');
68
+ }
69
+ /** The workspace record and physical root must agree, including inode identity. */
70
+ export async function validateRuntime(owner, runtime, allowRetiring = false) {
71
+ const container = await runtimeContainer();
72
+ if (!runtime ||
73
+ typeof runtime.directory !== 'string' ||
74
+ dirname(runtime.directory) !== container ||
75
+ !/^[0-9a-f]{20}$/.test(runtime.directory.slice(container.length + 1)) ||
76
+ Buffer.byteLength(runtime.directory) > runtimeRootMaxBytes ||
77
+ typeof runtime.token !== 'string' ||
78
+ !/^[0-9a-f]{64}$/.test(runtime.token) ||
79
+ typeof runtime.identity !== 'string' ||
80
+ !/^\d+:\d+:\d+$/.test(runtime.identity) ||
81
+ (runtime.retiring !== undefined && (runtime.retiring !== true || !allowRetiring)))
82
+ reject();
83
+ await privateDirectory(container, false);
84
+ try {
85
+ if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
86
+ reject();
87
+ }
88
+ 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')
92
+ return false;
93
+ throw error;
94
+ }
95
+ let actual;
96
+ try {
97
+ actual = await readMarker(join(runtime.directory, runtimeMarkerName));
98
+ }
99
+ catch (error) {
100
+ if (allowRetiring && runtime.retiring && error.code === 'ENOENT')
101
+ return true; // Cleanup may only rmdir this identity, never recursively delete it.
102
+ throw error;
103
+ }
104
+ if (JSON.stringify(actual) !== JSON.stringify(runtimeRecord(owner, runtime)))
105
+ reject();
106
+ return true;
107
+ }
108
+ /** A missing workspace does not authorize abandoning an external payload root. */
109
+ export async function hasRuntimeOwner(owner) {
110
+ const container = await runtimeContainer();
111
+ try {
112
+ await privateDirectory(container, false);
113
+ }
114
+ catch (error) {
115
+ if (error.code === 'ENOENT')
116
+ return false;
117
+ throw error;
118
+ }
119
+ const names = await readdir(container);
120
+ if (names.length > 10000)
121
+ reject();
122
+ for (const name of names) {
123
+ if (!/^[0-9a-f]{20}$/.test(name))
124
+ continue;
125
+ try {
126
+ await privateDirectory(join(container, name), false);
127
+ const record = (await readMarker(join(container, name, runtimeMarkerName)));
128
+ if (record.workspacePath === owner.workspacePath &&
129
+ (owner.ownerId === undefined || record.ownerId === owner.ownerId))
130
+ return true;
131
+ }
132
+ catch {
133
+ // Unattributable allocations stay untouched. They cannot establish
134
+ // ownership by this workspace or prevent unrelated sessions retiring.
135
+ continue;
136
+ }
137
+ }
138
+ return false;
139
+ }
140
+ /** Complete encoded endpoint, including its terminating NUL, must fit sun_path. */
141
+ export function requireSocketPath(path, capacity = { linux: 108, darwin: 104 }[process.platform]) {
142
+ if (!capacity)
143
+ throw new Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
144
+ if (path.includes('\0') || Buffer.byteLength(path) + 1 > capacity)
145
+ throw new Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name or temporary root');
146
+ return path;
147
+ }