gestalt-mobile 0.65.7 → 0.66.0

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 (55) hide show
  1. package/README.md +22 -0
  2. package/dist/client/assets/index-BDsGojoG.js +128 -0
  3. package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +2 -1
  6. package/dist/server/server/composition.contracts.js +179 -84
  7. package/dist/server/server/composition.js +65 -5
  8. package/dist/server/server/features/autopilot/application/service.js +19 -2
  9. package/dist/server/server/features/autopilot/domain/supervision-protocol.js +3 -0
  10. package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
  11. package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
  12. package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
  13. package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
  15. package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
  16. package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
  17. package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
  18. package/dist/server/server/features/sessions/register-routes.js +29 -2
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
  21. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
  22. package/dist/server/server/platform/codex/codex-playwright.js +41 -3
  23. package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
  24. package/dist/server/server/platform/codex/codex-serena.js +2 -1
  25. package/dist/server/server/platform/codex/managed-playwright.js +48 -36
  26. package/dist/server/server/platform/codex/session-runtime.js +134 -4
  27. package/dist/server/server/platform/git/command.js +7 -1
  28. package/dist/server/server/platform/host-tests/runner.js +47 -6
  29. package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
  30. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
  31. package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
  32. package/dist/server/server/platform/persistence/migrate.js +24 -0
  33. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
  34. package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
  35. package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
  36. package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
  37. package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
  38. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  39. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
  40. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +72 -2
  41. package/dist/server/server/platform/retrieval/xerj-indexer.js +104 -48
  42. package/dist/server/server/platform/scratch/child-environment.js +21 -0
  43. package/dist/server/server/platform/scratch/containment-fence.js +262 -0
  44. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +245 -0
  45. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
  46. package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
  47. package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
  48. package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
  49. package/dist/server/server/platform/scratch/owner-fence.js +27 -0
  50. package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
  51. package/dist/server/server/platform/self-debug/workspace.js +3 -0
  52. package/dist/server/shared/contracts/session-forget.js +6 -0
  53. package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
  54. package/package.json +1 -1
  55. package/dist/client/assets/index-CKJWzSwH.js +0 -128
@@ -0,0 +1,360 @@
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 { randomUUID } from 'node:crypto';
7
+ import { constants } from 'node:fs';
8
+ import { lstat, mkdir, open, readdir, realpath, rename, rmdir, unlink } from 'node:fs/promises';
9
+ import { isAbsolute, join, resolve } from 'node:path';
10
+ import { claimOwnerFence } from './owner-fence.js';
11
+ import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
12
+ export { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
13
+ import { withScratchContainment } from './containment-fence.js';
14
+ function validId(value) {
15
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(value))
16
+ throw new Error('SESSION_SCRATCH_INVALID_ID');
17
+ }
18
+ function validateMarker(value, expected) {
19
+ const marker = value;
20
+ if (!marker ||
21
+ marker.schemaVersion !== 1 ||
22
+ marker.ownerKind !== expected.ownerKind ||
23
+ marker.ownerId !== expected.ownerId ||
24
+ marker.workspacePath !== expected.workspacePath ||
25
+ marker.sessionId !== expected.sessionId ||
26
+ JSON.stringify(marker.authority) !== JSON.stringify(expected.authority) ||
27
+ typeof marker.createdAt !== 'string' ||
28
+ !Number.isFinite(Date.parse(marker.createdAt)) ||
29
+ !Array.isArray(marker.providerThreads) ||
30
+ marker.providerThreads.some((thread) => !thread ||
31
+ !['codex', 'kimi'].includes(thread.provider) ||
32
+ typeof thread.threadId !== 'string' ||
33
+ !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(thread.threadId)))
34
+ throw new Error('SESSION_SCRATCH_MARKER_MISMATCH');
35
+ return marker;
36
+ }
37
+ export class FilesystemSessionScratch {
38
+ assertAvailable;
39
+ pending = new Map();
40
+ constructor(assertAvailable = () => { }) {
41
+ this.assertAvailable = assertAvailable;
42
+ }
43
+ /** A live process claim remains protected across relay crashes and other servers. */
44
+ async borrow(session) {
45
+ validId(session.id);
46
+ this.assertAvailable(session.id);
47
+ return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
48
+ this.assertAvailable(session.id);
49
+ const { context, releaseFence } = await this.prepare(session);
50
+ try {
51
+ this.assertAvailable(session.id);
52
+ const leases = join(context.directory, 'leases');
53
+ await privateDirectory(leases, true);
54
+ const leaseId = randomUUID();
55
+ const path = join(leases, `${leaseId}.json`);
56
+ const record = {
57
+ schemaVersion: 1,
58
+ ownerId: context.ownerId,
59
+ workspacePath: context.workspacePath,
60
+ leaseId,
61
+ state: 'active',
62
+ processIdentity: randomUUID(),
63
+ createdAt: new Date().toISOString(),
64
+ updatedAt: new Date().toISOString(),
65
+ consumers: [`runtime-${randomUUID()}`],
66
+ };
67
+ const handle = await open(path, 'wx', 0o600);
68
+ try {
69
+ await handle.writeFile(JSON.stringify(record));
70
+ await handle.sync();
71
+ }
72
+ finally {
73
+ await handle.close();
74
+ }
75
+ let released = false;
76
+ return {
77
+ ...context,
78
+ release: async () => {
79
+ if (released)
80
+ return;
81
+ await privateDirectory(context.directory, false);
82
+ await privateDirectory(leases, false);
83
+ const current = (await readMarker(path));
84
+ if (current.schemaVersion !== 1 ||
85
+ current.ownerId !== record.ownerId ||
86
+ current.workspacePath !== record.workspacePath ||
87
+ current.processIdentity !== record.processIdentity ||
88
+ current.leaseId !== leaseId ||
89
+ current.state !== 'active' ||
90
+ current.createdAt !== record.createdAt ||
91
+ !Array.isArray(current.consumers) ||
92
+ JSON.stringify(current.consumers) !== JSON.stringify(record.consumers))
93
+ throw new Error('SESSION_SCRATCH_LEASE_CHANGED');
94
+ const staging = join(leases, `.${randomUUID()}.json`);
95
+ const file = await open(staging, 'wx', 0o600);
96
+ try {
97
+ await file.writeFile(JSON.stringify({
98
+ ...record,
99
+ state: 'released',
100
+ consumers: [],
101
+ updatedAt: new Date().toISOString(),
102
+ }));
103
+ await file.sync();
104
+ }
105
+ finally {
106
+ await file.close();
107
+ }
108
+ await rename(staging, path);
109
+ released = true;
110
+ },
111
+ };
112
+ }
113
+ finally {
114
+ await releaseFence();
115
+ }
116
+ }));
117
+ }
118
+ /** One lease per owned service process, independent of its first caller. */
119
+ async allocateService(workspacePath, consumer) {
120
+ validId(consumer);
121
+ return withScratchContainment(workspacePath, async () => {
122
+ const leaseId = randomUUID();
123
+ const ownerId = `service-${randomUUID()}`;
124
+ const { context, releaseFence } = await this.prepare({ id: ownerId, workspacePath }, leaseId);
125
+ const leases = join(context.directory, 'leases');
126
+ await privateDirectory(leases, true);
127
+ const path = join(leases, `${leaseId}.json`);
128
+ const record = {
129
+ schemaVersion: 1,
130
+ ownerId,
131
+ workspacePath: context.workspacePath,
132
+ leaseId,
133
+ state: 'active',
134
+ processIdentity: randomUUID(),
135
+ createdAt: new Date().toISOString(),
136
+ updatedAt: new Date().toISOString(),
137
+ consumers: [consumer],
138
+ };
139
+ const publish = async (initial) => {
140
+ const staging = initial ? path : join(leases, `.${randomUUID()}.json`);
141
+ const handle = await open(staging, 'wx', 0o600);
142
+ try {
143
+ await handle.writeFile(`${JSON.stringify(record)}\n`);
144
+ await handle.sync();
145
+ }
146
+ finally {
147
+ await handle.close();
148
+ }
149
+ if (!initial)
150
+ await rename(staging, path);
151
+ };
152
+ await publish(true);
153
+ let released = false;
154
+ return {
155
+ ...context,
156
+ release: async () => {
157
+ if (released)
158
+ return;
159
+ if ((await readdir(context.directory)).includes('.association-lock'))
160
+ throw new Error('SESSION_SCRATCH_BUSY');
161
+ for (const name of await readdir(leases)) {
162
+ if (name === `${leaseId}.json`)
163
+ continue;
164
+ const borrower = (await readMarker(join(leases, name)));
165
+ if (!borrower ||
166
+ borrower.schemaVersion !== 1 ||
167
+ borrower.ownerId !== ownerId ||
168
+ borrower.workspacePath !== context.workspacePath ||
169
+ borrower.state !== 'released' ||
170
+ typeof borrower.leaseId !== 'string' ||
171
+ name !== `${borrower.leaseId}.json` ||
172
+ typeof borrower.processIdentity !== 'string' ||
173
+ !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(borrower.processIdentity) ||
174
+ typeof borrower.createdAt !== 'string' ||
175
+ !Number.isFinite(Date.parse(borrower.createdAt)) ||
176
+ typeof borrower.updatedAt !== 'string' ||
177
+ !Number.isFinite(Date.parse(borrower.updatedAt)) ||
178
+ !Array.isArray(borrower.consumers) ||
179
+ borrower.consumers.length !== 0)
180
+ throw new Error('SESSION_SCRATCH_BORROWERS_ACTIVE');
181
+ }
182
+ record.state = 'released';
183
+ record.consumers = [];
184
+ record.updatedAt = new Date().toISOString();
185
+ await privateDirectory(context.directory, false);
186
+ await privateDirectory(leases, false);
187
+ await publish(false);
188
+ await releaseFence();
189
+ released = true;
190
+ },
191
+ };
192
+ });
193
+ }
194
+ async serialized(key, operation) {
195
+ const previous = this.pending.get(key);
196
+ const result = (previous ? previous.catch(() => undefined) : Promise.resolve()).then(operation);
197
+ this.pending.set(key, result);
198
+ try {
199
+ return await result;
200
+ }
201
+ finally {
202
+ if (this.pending.get(key) === result)
203
+ this.pending.delete(key);
204
+ }
205
+ }
206
+ async allocate(session) {
207
+ validId(session.id);
208
+ this.assertAvailable(session.id);
209
+ return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
210
+ this.assertAvailable(session.id);
211
+ const { context, releaseFence } = await this.prepare(session);
212
+ try {
213
+ this.assertAvailable(session.id);
214
+ return context;
215
+ }
216
+ finally {
217
+ await releaseFence();
218
+ }
219
+ }));
220
+ }
221
+ async associateProviderThread(session, provider, threadId) {
222
+ validId(session.id);
223
+ this.assertAvailable(session.id);
224
+ validId(threadId);
225
+ if (!['codex', 'kimi'].includes(provider))
226
+ throw new Error('SESSION_SCRATCH_INVALID_PROVIDER');
227
+ await this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
228
+ this.assertAvailable(session.id);
229
+ const { context, marker, releaseFence } = await this.prepare(session);
230
+ try {
231
+ if (marker.providerThreads.some((thread) => thread.provider === provider && thread.threadId === threadId))
232
+ return;
233
+ marker.providerThreads.push({ provider, threadId });
234
+ const staging = join(context.directory, `.owner-${randomUUID()}.json`);
235
+ const handle = await open(staging, 'wx', 0o600);
236
+ try {
237
+ await handle.writeFile(`${JSON.stringify(marker)}\n`);
238
+ await handle.sync();
239
+ await handle.close();
240
+ await privateDirectory(context.directory, false);
241
+ await rename(staging, join(context.directory, scratchMarkerName));
242
+ }
243
+ finally {
244
+ await handle.close();
245
+ await unlink(staging).catch((error) => {
246
+ if (error.code !== 'ENOENT')
247
+ throw error;
248
+ });
249
+ }
250
+ }
251
+ finally {
252
+ await releaseFence();
253
+ }
254
+ }));
255
+ }
256
+ async prepare(session, leaseId) {
257
+ const ownerId = leaseId ? session.id : mobileScratchOwnerId(session.id);
258
+ if (!isAbsolute(session.workspacePath))
259
+ throw new Error('SESSION_SCRATCH_WORKSPACE_REQUIRED');
260
+ const workspacePath = await realpath(session.workspacePath);
261
+ if (workspacePath !== resolve(session.workspacePath))
262
+ throw new Error('SESSION_SCRATCH_UNSAFE_WORKSPACE');
263
+ if (!(await lstat(workspacePath)).isDirectory())
264
+ throw new Error('SESSION_SCRATCH_WORKSPACE_REQUIRED');
265
+ const temporary = join(workspacePath, 'tmp');
266
+ // A user-owned tmp sibling may already be public; it is not ours to chmod.
267
+ try {
268
+ await mkdir(temporary, { mode: 0o700 });
269
+ }
270
+ catch (error) {
271
+ if (error.code !== 'EEXIST')
272
+ throw error;
273
+ }
274
+ const temporaryInfo = await lstat(temporary);
275
+ if (!temporaryInfo.isDirectory() ||
276
+ temporaryInfo.isSymbolicLink() ||
277
+ (await realpath(temporary)) !== temporary ||
278
+ (process.getuid && temporaryInfo.uid !== process.getuid()))
279
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
280
+ const sessions = join(temporary, 'sessions');
281
+ await privateDirectory(sessions, true);
282
+ // Git ignores this file too. Existing user rules are never replaced.
283
+ const ignore = await open(join(sessions, '.gitignore'), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600).catch((error) => {
284
+ if (error.code !== 'EEXIST')
285
+ throw error;
286
+ return undefined;
287
+ });
288
+ if (ignore) {
289
+ try {
290
+ await ignore.writeFile('*\n');
291
+ }
292
+ finally {
293
+ await ignore.close();
294
+ }
295
+ }
296
+ const directory = join(sessions, ownerId);
297
+ const created = await privateDirectory(directory, true);
298
+ const releaseFence = await claimOwnerFence(directory);
299
+ try {
300
+ const markerPath = join(directory, scratchMarkerName);
301
+ const expected = {
302
+ schemaVersion: 1,
303
+ ownerKind: leaseId ? 'workspace-service' : 'mobile-session',
304
+ ownerId,
305
+ workspacePath,
306
+ sessionId: session.id,
307
+ createdAt: new Date().toISOString(),
308
+ authority: leaseId
309
+ ? { kind: 'lease', leaseId }
310
+ : { kind: 'mobile-roster', sessionId: session.id },
311
+ providerThreads: [],
312
+ };
313
+ let marker;
314
+ if (created) {
315
+ try {
316
+ const handle = await open(markerPath, 'wx', 0o600);
317
+ try {
318
+ await handle.writeFile(`${JSON.stringify(expected)}\n`);
319
+ await handle.sync();
320
+ }
321
+ finally {
322
+ await handle.close();
323
+ }
324
+ marker = expected;
325
+ }
326
+ catch (error) {
327
+ // Remove only this invocation's still-empty allocation; preserve uncertainty.
328
+ await rmdir(directory).catch(() => undefined);
329
+ throw error;
330
+ }
331
+ }
332
+ else {
333
+ marker = validateMarker(await readMarker(markerPath), expected);
334
+ }
335
+ await privateDirectory(directory, false);
336
+ const context = {
337
+ workspacePath,
338
+ ownerId,
339
+ directory,
340
+ environment: {
341
+ TMPDIR: directory,
342
+ TMP: directory,
343
+ TEMP: directory,
344
+ [scratchContextVariable]: JSON.stringify({
345
+ schemaVersion: 1,
346
+ workspacePath,
347
+ ownerId,
348
+ directory,
349
+ markerPath,
350
+ }),
351
+ },
352
+ };
353
+ return { context, marker, releaseFence };
354
+ }
355
+ catch (error) {
356
+ await releaseFence();
357
+ throw error;
358
+ }
359
+ }
360
+ }
@@ -0,0 +1,22 @@
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
+ /** Historical producer names are discovery hints only. None establish ownership
7
+ * or release; these candidates are retained. See docs/legacy-scratch-provenance.md.
8
+ */
9
+ const legacyPrefixes = [
10
+ '.ctx-mode-',
11
+ 'gestalt-cli-playwright-',
12
+ 'gestalt-xerj-regression-',
13
+ 'gestalt-sandbox-doctor-',
14
+ 'gestalt-serena-doctor-',
15
+ 'gestalt-chrome.',
16
+ 'gestalt-skills-export.',
17
+ 'gestalt-skills-import.',
18
+ 'gestalt-update.',
19
+ ];
20
+ export function isAmbiguousLegacyScratch(name) {
21
+ return legacyPrefixes.some((prefix) => name.startsWith(prefix) && name.length > prefix.length);
22
+ }
@@ -0,0 +1,148 @@
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 { lstat, readdir, realpath } from 'node:fs/promises';
7
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
8
+ import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, } from './scratch-filesystem.js';
9
+ export const scratchUuidPattern = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
10
+ const ownerPattern = `(?:mobile-[0-9a-f]{64}|(?:cli|service)-${scratchUuidPattern})`;
11
+ const ownerName = new RegExp(`^${ownerPattern}$`);
12
+ const removalName = new RegExp(`^\\.cleanup-(${ownerPattern})-${scratchUuidPattern}$`);
13
+ const isUuid = new RegExp(`^${scratchUuidPattern}$`);
14
+ const leaseName = new RegExp(`^(${scratchUuidPattern})\\.json$`);
15
+ const stableId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
16
+ const validTime = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
17
+ export function managedScratchOwnerId(name) {
18
+ return ownerName.test(name) ? name : removalName.exec(name)?.[1];
19
+ }
20
+ export async function canonicalScratchWorkspace(path) {
21
+ if (!isAbsolute(path))
22
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
23
+ const canonical = await realpath(path);
24
+ const info = await lstat(path);
25
+ if (canonical !== resolve(path) ||
26
+ !info.isDirectory() ||
27
+ info.isSymbolicLink() ||
28
+ (process.getuid && info.uid !== process.getuid()))
29
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
30
+ return canonical;
31
+ }
32
+ function rejectOwner() {
33
+ throw new Error('SCRATCH_CLEANUP_unrecognized');
34
+ }
35
+ /** Metadata recognition alone never authorizes deletion: leases, roster and fences still apply. */
36
+ export async function readManagedScratchOwner(directory, workspacePath, ownerId) {
37
+ let marker;
38
+ try {
39
+ marker = (await readMarker(join(directory, scratchMarkerName)));
40
+ }
41
+ catch (error) {
42
+ if (error.code === 'ENOENT')
43
+ rejectOwner();
44
+ throw error;
45
+ }
46
+ if (!marker ||
47
+ marker.schemaVersion !== 1 ||
48
+ marker.ownerId !== ownerId ||
49
+ marker.workspacePath !== workspacePath ||
50
+ !validTime(marker.createdAt) ||
51
+ !Array.isArray(marker.providerThreads) ||
52
+ marker.providerThreads.some((thread) => !thread ||
53
+ !['codex', 'kimi'].includes(thread.provider) ||
54
+ typeof thread.threadId !== 'string' ||
55
+ !stableId.test(thread.threadId)))
56
+ rejectOwner();
57
+ if (marker.ownerKind === 'mobile-session') {
58
+ if (typeof marker.sessionId !== 'string' ||
59
+ !stableId.test(marker.sessionId) ||
60
+ mobileScratchOwnerId(marker.sessionId) !== ownerId ||
61
+ marker.authority?.kind !== 'mobile-roster' ||
62
+ marker.authority.sessionId !== marker.sessionId)
63
+ rejectOwner();
64
+ }
65
+ else if (marker.ownerKind === 'cli-session' || marker.ownerKind === 'workspace-service') {
66
+ const prefix = marker.ownerKind === 'cli-session' ? 'cli-' : 'service-';
67
+ if (!ownerId.startsWith(prefix) ||
68
+ marker.sessionId !== ownerId ||
69
+ marker.authority?.kind !== 'lease' ||
70
+ !isUuid.test(marker.authority.leaseId ?? ''))
71
+ rejectOwner();
72
+ }
73
+ else
74
+ rejectOwner();
75
+ return marker;
76
+ }
77
+ /** Attribution is read-only; it does not prove release or supply deletion authority. */
78
+ export async function readManagedScratchAttribution(directory, allowRetired = false) {
79
+ const container = dirname(directory);
80
+ const temporary = dirname(container);
81
+ const name = basename(directory);
82
+ const ownerId = managedScratchOwnerId(name);
83
+ if (basename(container) !== 'sessions' ||
84
+ basename(temporary) !== 'tmp' ||
85
+ !ownerId ||
86
+ (!allowRetired && ownerId !== name))
87
+ rejectOwner();
88
+ const workspacePath = dirname(temporary);
89
+ await canonicalScratchWorkspace(workspacePath);
90
+ const info = await lstat(temporary);
91
+ if (!info.isDirectory() ||
92
+ info.isSymbolicLink() ||
93
+ (await realpath(temporary)) !== temporary ||
94
+ (process.getuid && info.uid !== process.getuid()))
95
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
96
+ await privateDirectory(container, false);
97
+ await privateDirectory(directory, false);
98
+ const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
99
+ return { directory, workspacePath, ownerId, marker };
100
+ }
101
+ function rejectLease() {
102
+ throw new Error('SESSION_SCRATCH_LEASE_INVALID');
103
+ }
104
+ export async function readManagedScratchLeases(directory, marker) {
105
+ if (!(await readdir(directory)).includes('leases')) {
106
+ if (marker.ownerKind !== 'mobile-session')
107
+ rejectLease();
108
+ return [];
109
+ }
110
+ const leases = join(directory, 'leases');
111
+ await privateDirectory(leases, false);
112
+ const records = [];
113
+ for (const name of await readdir(leases)) {
114
+ const leaseId = leaseName.exec(name)?.[1];
115
+ if (!leaseId)
116
+ rejectLease();
117
+ const value = (await readMarker(join(leases, name)));
118
+ if (!value ||
119
+ value.schemaVersion !== 1 ||
120
+ value.ownerId !== marker.ownerId ||
121
+ value.workspacePath !== marker.workspacePath ||
122
+ value.leaseId !== leaseId ||
123
+ typeof value.processIdentity !== 'string' ||
124
+ !isUuid.test(value.processIdentity) ||
125
+ !validTime(value.createdAt) ||
126
+ !validTime(value.updatedAt) ||
127
+ !['active', 'released'].includes(value.state) ||
128
+ !Array.isArray(value.consumers) ||
129
+ !value.consumers.every((consumer) => typeof consumer === 'string' && stableId.test(consumer)) ||
130
+ (value.state === 'released' && value.consumers.length !== 0))
131
+ rejectLease();
132
+ records.push(value);
133
+ }
134
+ if (marker.ownerKind !== 'mobile-session' &&
135
+ !records.some((lease) => lease.leaseId === marker.authority.leaseId))
136
+ rejectLease();
137
+ return records;
138
+ }
139
+ /** Discovery excludes only attributed scratch; unknown/plain directories remain discoverable. */
140
+ export async function isManagedScratchOwnerDirectory(directory) {
141
+ try {
142
+ await readManagedScratchAttribution(directory, true);
143
+ return true;
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ }
@@ -0,0 +1,53 @@
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 { setTimeout as delay } from 'node:timers/promises';
7
+ /** Only for a group created by this runtime with detached:true; never persisted PIDs. */
8
+ export async function stopOwnedProcessGroup(child, graceMs = 2000, confirmationMs = 1000) {
9
+ if (process.platform === 'win32')
10
+ return false;
11
+ if (!child.pid) {
12
+ if (child.exitCode === null && child.signalCode === null)
13
+ child.kill('SIGTERM');
14
+ return false;
15
+ }
16
+ const group = -child.pid;
17
+ const signal = (value) => {
18
+ try {
19
+ process.kill(group, value);
20
+ return 'present';
21
+ }
22
+ catch (error) {
23
+ return error.code === 'ESRCH' ? 'absent' : 'unknown';
24
+ }
25
+ };
26
+ const wait = async (timeout) => {
27
+ const deadline = Date.now() + timeout;
28
+ for (;;) {
29
+ const status = signal(0);
30
+ if (status !== 'present')
31
+ return status;
32
+ if (Date.now() >= deadline)
33
+ return 'present';
34
+ await delay(Math.min(20, deadline - Date.now()));
35
+ }
36
+ };
37
+ // Once the leader was already reaped, its numeric group ID may have been reused.
38
+ // Read-only absence can prove release; a present group cannot prove ownership.
39
+ if (child.exitCode !== null || child.signalCode !== null)
40
+ return (await wait(confirmationMs)) === 'absent';
41
+ const term = signal('SIGTERM');
42
+ if (term !== 'present')
43
+ return term === 'absent';
44
+ const graceful = await wait(graceMs);
45
+ if (graceful !== 'present')
46
+ return graceful === 'absent';
47
+ if (child.exitCode !== null || child.signalCode !== null)
48
+ return (await wait(confirmationMs)) === 'absent';
49
+ const forced = signal('SIGKILL');
50
+ if (forced !== 'present')
51
+ return forced === 'absent';
52
+ return (await wait(confirmationMs)) === 'absent';
53
+ }
@@ -0,0 +1,27 @@
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 { lstat, mkdir, rmdir } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ /** An absent fence can be claimed; an existing one is never retired by age or PID. */
9
+ export async function claimOwnerFence(directory) {
10
+ const path = join(directory, '.controller-lock');
11
+ try {
12
+ await mkdir(path, { mode: 0o700 });
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'EEXIST')
16
+ throw new Error('SESSION_SCRATCH_BUSY');
17
+ throw error;
18
+ }
19
+ const identity = await lstat(path);
20
+ return async (at = directory) => {
21
+ const currentPath = join(at, '.controller-lock');
22
+ const current = await lstat(currentPath);
23
+ if (current.dev !== identity.dev || current.ino !== identity.ino || !current.isDirectory())
24
+ throw new Error('SESSION_SCRATCH_FENCE_CHANGED');
25
+ await rmdir(currentPath);
26
+ };
27
+ }
@@ -0,0 +1,53 @@
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 { createHash } from 'node:crypto';
7
+ import { constants } from 'node:fs';
8
+ import { lstat, mkdir, open, realpath } from 'node:fs/promises';
9
+ export const scratchMarkerName = '.gestalt-owner.json';
10
+ export const scratchContextVariable = 'GESTALT_SESSION_TMP_CONTEXT';
11
+ export function mobileScratchOwnerId(sessionId) {
12
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(sessionId))
13
+ throw new Error('SESSION_SCRATCH_INVALID_ID');
14
+ return `mobile-${createHash('sha256').update(sessionId).digest('hex')}`;
15
+ }
16
+ /** Reject links and foreign directories; never repair their permissions or contents. */
17
+ export async function privateDirectory(path, create) {
18
+ let created = false;
19
+ if (create) {
20
+ try {
21
+ await mkdir(path, { mode: 0o700 });
22
+ created = true;
23
+ }
24
+ catch (error) {
25
+ if (error.code !== 'EEXIST')
26
+ throw error;
27
+ }
28
+ }
29
+ const info = await lstat(path);
30
+ if (!info.isDirectory() || info.isSymbolicLink() || (await realpath(path)) !== path)
31
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
32
+ if (process.getuid && info.uid !== process.getuid())
33
+ throw new Error('SESSION_SCRATCH_FOREIGN_OWNER');
34
+ if (process.platform !== 'win32' && (info.mode & 0o777) !== 0o700)
35
+ throw new Error('SESSION_SCRATCH_NOT_PRIVATE');
36
+ return created;
37
+ }
38
+ export async function readMarker(path) {
39
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
40
+ try {
41
+ const info = await handle.stat();
42
+ if (!info.isFile() ||
43
+ info.nlink !== 1 ||
44
+ info.size > 16384 ||
45
+ (process.getuid && info.uid !== process.getuid()) ||
46
+ (process.platform !== 'win32' && (info.mode & 0o077) !== 0))
47
+ throw new Error('SESSION_SCRATCH_UNSAFE_MARKER');
48
+ return JSON.parse(await handle.readFile('utf8'));
49
+ }
50
+ finally {
51
+ await handle.close();
52
+ }
53
+ }