gestalt-mobile 0.65.8 → 0.66.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.
- package/README.md +28 -4
- package/dist/client/assets/index-BDsGojoG.js +128 -0
- package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/server/cli.js +2 -1
- package/dist/server/server/composition.contracts.js +179 -84
- package/dist/server/server/composition.js +65 -5
- package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
- package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
- package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
- package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
- package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
- package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
- package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
- package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
- package/dist/server/server/features/sessions/register-routes.js +29 -2
- package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
- package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
- package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
- package/dist/server/server/platform/codex/codex-playwright.js +41 -3
- package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
- package/dist/server/server/platform/codex/codex-serena.js +2 -1
- package/dist/server/server/platform/codex/managed-playwright.js +48 -36
- package/dist/server/server/platform/codex/session-runtime.js +134 -4
- package/dist/server/server/platform/git/command.js +7 -1
- package/dist/server/server/platform/host-tests/runner.js +47 -6
- package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
- package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
- package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
- package/dist/server/server/platform/persistence/migrate.js +24 -0
- package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
- package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
- package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
- package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
- package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
- package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
- package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
- package/dist/server/server/platform/retrieval/xerj-indexer.js +21 -11
- package/dist/server/server/platform/scratch/child-environment.js +21 -0
- package/dist/server/server/platform/scratch/containment-fence.js +262 -0
- package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +247 -0
- package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
- package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
- package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
- package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
- package/dist/server/server/platform/scratch/owner-fence.js +27 -0
- package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
- package/dist/server/server/platform/self-debug/workspace.js +3 -0
- package/dist/server/shared/contracts/session-forget.js +6 -0
- package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
- package/package.json +1 -1
- package/dist/client/assets/index-CKJWzSwH.js +0 -128
|
@@ -0,0 +1,247 @@
|
|
|
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 { lstat, mkdir, opendir, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
|
|
8
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
9
|
+
import { emptyScratchCounts, } from '../../features/sessions/clean-tmp/use-case.js';
|
|
10
|
+
import { mobileScratchOwnerId, privateDirectory, scratchMarkerName } from './scratch-filesystem.js';
|
|
11
|
+
import { claimOwnerFence } from './owner-fence.js';
|
|
12
|
+
import { isAmbiguousLegacyScratch } from './legacy-scratch-layouts.js';
|
|
13
|
+
import { canonicalScratchWorkspace, managedScratchOwnerId, readManagedScratchOwner, readManagedScratchLeases, } from './managed-scratch-owner.js';
|
|
14
|
+
import { claimScratchContainment, containmentFenceName } from './containment-fence.js';
|
|
15
|
+
function reject(reason) {
|
|
16
|
+
throw new Error(`SCRATCH_CLEANUP_${reason}`);
|
|
17
|
+
}
|
|
18
|
+
/** Only the managed namespace is traversed. There are no prefix/age/PID legacy recognizers. */
|
|
19
|
+
export class FilesystemScratchCleanup {
|
|
20
|
+
async cleanSession(session, authorized, protectedSessions) {
|
|
21
|
+
const counts = await this.cleanWorkspace(session.workspacePath, protectedSessions, mobileScratchOwnerId(session.id), authorized);
|
|
22
|
+
if (counts.skipped || counts.failed)
|
|
23
|
+
throw new Error('SESSION_CLEANUP_FAILED');
|
|
24
|
+
}
|
|
25
|
+
async canonicalWorkspace(path) {
|
|
26
|
+
return canonicalScratchWorkspace(path);
|
|
27
|
+
}
|
|
28
|
+
async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized) {
|
|
29
|
+
await this.canonicalWorkspace(workspacePath);
|
|
30
|
+
const counts = emptyScratchCounts();
|
|
31
|
+
const temporary = join(workspacePath, 'tmp');
|
|
32
|
+
try {
|
|
33
|
+
const info = await lstat(temporary);
|
|
34
|
+
if (!info.isDirectory() ||
|
|
35
|
+
info.isSymbolicLink() ||
|
|
36
|
+
(await realpath(temporary)) !== temporary ||
|
|
37
|
+
(process.getuid && info.uid !== process.getuid()))
|
|
38
|
+
throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error.code === 'ENOENT')
|
|
42
|
+
return counts;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
if (!onlyOwnerId) {
|
|
46
|
+
for (const entry of await readdir(temporary, { withFileTypes: true })) {
|
|
47
|
+
if (!isAmbiguousLegacyScratch(entry.name) ||
|
|
48
|
+
(!entry.isDirectory() && !entry.isSymbolicLink()))
|
|
49
|
+
continue;
|
|
50
|
+
counts.skipped++;
|
|
51
|
+
counts.reasons[entry.isSymbolicLink() ? 'unsafe' : 'unrecognized']++;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const container = join(temporary, 'sessions');
|
|
55
|
+
try {
|
|
56
|
+
await privateDirectory(container, false);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (error.code === 'ENOENT')
|
|
60
|
+
return counts;
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
for (const name of await readdir(container)) {
|
|
64
|
+
if (name === '.gitignore')
|
|
65
|
+
continue;
|
|
66
|
+
if (onlyOwnerId && managedScratchOwnerId(name) !== onlyOwnerId)
|
|
67
|
+
continue;
|
|
68
|
+
let release;
|
|
69
|
+
let containment;
|
|
70
|
+
let directory = join(container, name);
|
|
71
|
+
let outcome;
|
|
72
|
+
try {
|
|
73
|
+
const ownerId = managedScratchOwnerId(name);
|
|
74
|
+
if (!ownerId)
|
|
75
|
+
reject('unrecognized');
|
|
76
|
+
await privateDirectory(directory, false);
|
|
77
|
+
// A removal reservation/partial allocation is not an owner yet. Inspect
|
|
78
|
+
// its locator before claiming a fence; authority is rechecked below.
|
|
79
|
+
await readManagedScratchOwner(directory, workspacePath, ownerId);
|
|
80
|
+
containment = await claimScratchContainment(directory, ownerId);
|
|
81
|
+
release = await claimOwnerFence(directory);
|
|
82
|
+
const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
|
|
83
|
+
await this.releasedLeases(directory, marker);
|
|
84
|
+
await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
|
|
85
|
+
await this.validatePayload(directory);
|
|
86
|
+
await privateDirectory(directory, false);
|
|
87
|
+
await containment.revalidate();
|
|
88
|
+
if (name === ownerId) {
|
|
89
|
+
const retired = join(container, `.cleanup-${ownerId}-${randomUUID()}`);
|
|
90
|
+
// Reserve the random destination exclusively; never replace a collision.
|
|
91
|
+
await mkdir(retired, { mode: 0o700 });
|
|
92
|
+
try {
|
|
93
|
+
await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
await rmdir(retired);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
await rename(directory, retired);
|
|
100
|
+
directory = retired;
|
|
101
|
+
// The fence moved with the owner. Never release a replacement at its old path.
|
|
102
|
+
const claimed = release;
|
|
103
|
+
release = () => claimed(retired);
|
|
104
|
+
await containment.relocate(join(container, name), retired);
|
|
105
|
+
}
|
|
106
|
+
await privateDirectory(directory, false);
|
|
107
|
+
await containment.revalidate();
|
|
108
|
+
await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
|
|
109
|
+
// Keep authority metadata until disposable payload has been removed. A failed
|
|
110
|
+
// payload deletion is retryable; an interrupted metadata retirement is unknown.
|
|
111
|
+
for (const child of await readdir(directory)) {
|
|
112
|
+
if ([scratchMarkerName, 'leases', '.controller-lock', containmentFenceName].includes(child))
|
|
113
|
+
continue;
|
|
114
|
+
await rm(join(directory, child), { recursive: true });
|
|
115
|
+
}
|
|
116
|
+
if ((await readdir(directory)).includes('leases'))
|
|
117
|
+
await rm(join(directory, 'leases'), { recursive: true });
|
|
118
|
+
await rm(join(directory, scratchMarkerName));
|
|
119
|
+
// With marker/payload retired, no publisher can validate this namespace.
|
|
120
|
+
// Remove only our own fence instances, then the still-empty owner directory.
|
|
121
|
+
await release();
|
|
122
|
+
release = undefined;
|
|
123
|
+
await containment.retireCurrent(directory, () => rmdir(directory));
|
|
124
|
+
counts.removed++;
|
|
125
|
+
outcome = 'removed';
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
const code = error.code;
|
|
129
|
+
const message = error instanceof Error ? error.message : '';
|
|
130
|
+
const reason = message.startsWith('SCRATCH_CLEANUP_')
|
|
131
|
+
? message.slice('SCRATCH_CLEANUP_'.length)
|
|
132
|
+
: error instanceof SyntaxError
|
|
133
|
+
? 'unrecognized'
|
|
134
|
+
: message === 'SESSION_SCRATCH_LEASE_INVALID'
|
|
135
|
+
? 'lease'
|
|
136
|
+
: ['SESSION_SCRATCH_BUSY', 'SESSION_SCRATCH_CONTAINMENT_BUSY'].includes(message)
|
|
137
|
+
? 'busy'
|
|
138
|
+
: message.startsWith('SESSION_SCRATCH_') ||
|
|
139
|
+
['ELOOP', 'ENOTDIR'].includes(code ?? '')
|
|
140
|
+
? 'unsafe'
|
|
141
|
+
: code === 'ENOENT'
|
|
142
|
+
? 'busy'
|
|
143
|
+
: 'io';
|
|
144
|
+
counts.reasons[reason]++;
|
|
145
|
+
outcome = reason === 'io' ? 'failed' : 'skipped';
|
|
146
|
+
counts[outcome]++;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
if (release) {
|
|
150
|
+
try {
|
|
151
|
+
await release();
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
if (outcome !== 'failed') {
|
|
155
|
+
if (outcome)
|
|
156
|
+
counts[outcome]--;
|
|
157
|
+
counts.failed++;
|
|
158
|
+
outcome = 'failed';
|
|
159
|
+
}
|
|
160
|
+
counts.reasons.io++;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (containment) {
|
|
164
|
+
try {
|
|
165
|
+
await containment.release();
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
if (outcome !== 'failed') {
|
|
169
|
+
if (outcome)
|
|
170
|
+
counts[outcome]--;
|
|
171
|
+
counts.failed++;
|
|
172
|
+
outcome = 'failed';
|
|
173
|
+
}
|
|
174
|
+
counts.reasons.io++;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return counts;
|
|
180
|
+
}
|
|
181
|
+
async releasedLeases(directory, marker) {
|
|
182
|
+
if ((await readdir(directory)).includes('.association-lock'))
|
|
183
|
+
reject('busy');
|
|
184
|
+
const leases = await readManagedScratchLeases(directory, marker);
|
|
185
|
+
if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0))
|
|
186
|
+
reject('lease');
|
|
187
|
+
}
|
|
188
|
+
async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized) {
|
|
189
|
+
if (authorized && !authorized())
|
|
190
|
+
reject('protected');
|
|
191
|
+
const within = (root, path) => {
|
|
192
|
+
const suffix = relative(root, path);
|
|
193
|
+
return (suffix === '' || (!isAbsolute(suffix) && suffix !== '..' && !suffix.startsWith(`..${sep}`)));
|
|
194
|
+
};
|
|
195
|
+
for (const session of protectedSessions()) {
|
|
196
|
+
// Only this exact targeted owner's authorized Forget may exclude itself.
|
|
197
|
+
if (authorized && marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
|
|
198
|
+
continue;
|
|
199
|
+
if (marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
|
|
200
|
+
reject('protected');
|
|
201
|
+
if (!isAbsolute(session.workspacePath))
|
|
202
|
+
reject('unrecognized');
|
|
203
|
+
const paths = new Set([resolve(session.workspacePath)]);
|
|
204
|
+
try {
|
|
205
|
+
paths.add(await realpath(session.workspacePath));
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// Durable canonical locators remain protective even after a retirement.
|
|
209
|
+
// Missing unrelated workspaces are reported by their own scan.
|
|
210
|
+
}
|
|
211
|
+
for (const workspace of paths) {
|
|
212
|
+
const scratch = join(workspace, 'tmp', 'sessions', mobileScratchOwnerId(session.id));
|
|
213
|
+
if ([directory, logicalDirectory].some((owner) => within(owner, workspace) || within(owner, scratch)))
|
|
214
|
+
reject('protected');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async validatePayload(directory, root = directory, depth = 0, budget = { entries: 0 }) {
|
|
219
|
+
if (depth > 128)
|
|
220
|
+
reject('unrecognized');
|
|
221
|
+
// Even an empty nested namespace is not authority to retire a workspace's
|
|
222
|
+
// contents recursively as another owner's payload.
|
|
223
|
+
if (directory !== root &&
|
|
224
|
+
basename(directory) === 'sessions' &&
|
|
225
|
+
basename(dirname(directory)) === 'tmp')
|
|
226
|
+
reject('unrecognized');
|
|
227
|
+
for await (const entry of await opendir(directory)) {
|
|
228
|
+
const child = entry.name;
|
|
229
|
+
if (++budget.entries > 100_000)
|
|
230
|
+
reject('unrecognized');
|
|
231
|
+
if (directory !== root &&
|
|
232
|
+
[scratchMarkerName, '.controller-lock', '.association-lock', containmentFenceName].includes(child))
|
|
233
|
+
reject('unrecognized');
|
|
234
|
+
const path = join(directory, child);
|
|
235
|
+
const info = await lstat(path);
|
|
236
|
+
if ((process.getuid && info.uid !== process.getuid()) ||
|
|
237
|
+
(!info.isDirectory() && !info.isFile() && !info.isSymbolicLink()) ||
|
|
238
|
+
(info.isFile() && info.nlink !== 1))
|
|
239
|
+
reject('unsafe');
|
|
240
|
+
// Payload symlinks (for example npm's .bin entries) are disposable links.
|
|
241
|
+
// lstat never follows them, and rm unlinks them without deleting their targets.
|
|
242
|
+
// Owner paths and authority metadata retain their separate no-link checks.
|
|
243
|
+
if (info.isDirectory())
|
|
244
|
+
await this.validatePayload(path, root, depth + 1, budget);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -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
|
+
}
|