@jaromil/gestalt 0.15.1 → 0.16.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 +6 -0
- package/lib/gestalt +385 -1492
- package/package.json +2 -2
package/lib/gestalt
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
set -Eeuo pipefail
|
|
4
4
|
IFS=$'\n\t'
|
|
5
5
|
|
|
6
|
-
readonly GESTALT_CLI_VERSION='0.
|
|
6
|
+
readonly GESTALT_CLI_VERSION='0.16.1'
|
|
7
7
|
readonly DEFAULT_INSTALL_BASE_URL='https://dyne.github.io/gestalt'
|
|
8
8
|
readonly DEFAULT_MARKETPLACE='dyne/gestalt-agents'
|
|
9
9
|
readonly DEFAULT_MARKETPLACE_NAME='dyne-gestalt-agents'
|
|
@@ -16,8 +16,6 @@ readonly DEFAULT_SKILLS_REF='main'
|
|
|
16
16
|
serena_install_candidate=''
|
|
17
17
|
serena_install_lock=''
|
|
18
18
|
serena_install_process_pid=''
|
|
19
|
-
xerj_install_scratch=''
|
|
20
|
-
xerj_config_scratch=''
|
|
21
19
|
manager_update_temp_root=''
|
|
22
20
|
manager_update_staged_target=''
|
|
23
21
|
manager_update_resumed=false
|
|
@@ -26,7 +24,6 @@ skills_transfer_temp_root=''
|
|
|
26
24
|
skills_export_staged_target=''
|
|
27
25
|
doctor_sandbox_report=''
|
|
28
26
|
codex_approval_launcher=''
|
|
29
|
-
session_tmp_owner_kind=''
|
|
30
27
|
|
|
31
28
|
log() {
|
|
32
29
|
printf 'gestalt: %s\n' "$*" >&2
|
|
@@ -64,12 +61,6 @@ JS
|
|
|
64
61
|
if [[ -n $serena_install_lock && -d $serena_install_lock ]]; then
|
|
65
62
|
rmdir -- "$serena_install_lock" 2>/dev/null || true
|
|
66
63
|
fi
|
|
67
|
-
if [[ -n $xerj_config_scratch && -f $xerj_config_scratch ]]; then
|
|
68
|
-
rm -f -- "$xerj_config_scratch"
|
|
69
|
-
fi
|
|
70
|
-
if [[ -n $xerj_install_scratch && -d $xerj_install_scratch ]]; then
|
|
71
|
-
rm -rf -- "$xerj_install_scratch"
|
|
72
|
-
fi
|
|
73
64
|
if [[ -n $manager_update_temp_root && -d $manager_update_temp_root ]]; then
|
|
74
65
|
rm -rf -- "$manager_update_temp_root"
|
|
75
66
|
fi
|
|
@@ -128,10 +119,92 @@ function scratchJson(file) {
|
|
|
128
119
|
return JSON.parse(scratchFs.readFileSync(fd, 'utf8'));
|
|
129
120
|
} finally { scratchFs.closeSync(fd); }
|
|
130
121
|
}
|
|
122
|
+
function scratchRuntimeContainer() {
|
|
123
|
+
scratchAssert(typeof process.getuid === 'function');
|
|
124
|
+
return scratchPath.join(scratchFs.realpathSync('/tmp'), 'gs-' + process.getuid());
|
|
125
|
+
}
|
|
126
|
+
function scratchRuntimeIdentity(directory) {
|
|
127
|
+
scratchPrivate(directory);
|
|
128
|
+
const info = scratchFs.lstatSync(directory, {bigint:true});
|
|
129
|
+
return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
|
|
130
|
+
}
|
|
131
|
+
function scratchRuntimeRecord(owner, runtime) {
|
|
132
|
+
return {schemaVersion:2,ownerId:owner.ownerId,workspacePath:owner.workspacePath,token:runtime.token,identity:runtime.identity};
|
|
133
|
+
}
|
|
134
|
+
function scratchAllocateRuntime(owner) {
|
|
135
|
+
const container = scratchRuntimeContainer();
|
|
136
|
+
try {scratchFs.mkdirSync(container,{mode:0o700});} catch(error) {if(error.code!=='EEXIST')throw error;}
|
|
137
|
+
scratchPrivate(container);
|
|
138
|
+
for(let attempt=0;attempt<16;attempt++) {
|
|
139
|
+
const directory=scratchPath.join(container,scratchCrypto.randomBytes(10).toString('hex'));
|
|
140
|
+
if(Buffer.byteLength(directory)>48)throw Error('SESSION_SCRATCH_RUNTIME_ROOT_TOO_LONG');
|
|
141
|
+
try {scratchFs.mkdirSync(directory,{mode:0o700});} catch(error) {if(error.code==='EEXIST')continue;throw error;}
|
|
142
|
+
const runtime={directory,token:scratchCrypto.randomBytes(32).toString('hex'),identity:scratchRuntimeIdentity(directory)};
|
|
143
|
+
scratchPublish(scratchPath.join(directory,'.gestalt-runtime.json'),scratchRuntimeRecord(owner,runtime),true);
|
|
144
|
+
return runtime;
|
|
145
|
+
}
|
|
146
|
+
throw Error('SESSION_SCRATCH_RUNTIME_COLLISION');
|
|
147
|
+
}
|
|
148
|
+
function scratchValidateRuntime(owner,runtime) {
|
|
149
|
+
const container=scratchRuntimeContainer();
|
|
150
|
+
scratchAssert(runtime && typeof runtime.directory==='string' && scratchPath.dirname(runtime.directory)===container &&
|
|
151
|
+
/^[0-9a-f]{20}$/.test(scratchPath.basename(runtime.directory)) && Buffer.byteLength(runtime.directory)<=48 &&
|
|
152
|
+
typeof runtime.token==='string' && /^[0-9a-f]{64}$/.test(runtime.token) &&
|
|
153
|
+
typeof runtime.identity==='string' && /^\d+:\d+:\d+$/.test(runtime.identity) && runtime.retiring===undefined);
|
|
154
|
+
scratchPrivate(container);
|
|
155
|
+
scratchAssert(scratchRuntimeIdentity(runtime.directory)===runtime.identity &&
|
|
156
|
+
JSON.stringify(scratchJson(scratchPath.join(runtime.directory,'.gestalt-runtime.json')))===JSON.stringify(scratchRuntimeRecord(owner,runtime)));
|
|
157
|
+
}
|
|
158
|
+
function scratchTemporaryDirectory(context) {return context.runtime?.directory ?? context.directory;}
|
|
159
|
+
function scratchSocketPath(endpoint,capacity=({linux:108,darwin:104})[process.platform]) {
|
|
160
|
+
if(!capacity)throw Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
|
|
161
|
+
if(endpoint.includes('\0') || Buffer.byteLength(endpoint)+1>capacity)
|
|
162
|
+
throw Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name or temporary root');
|
|
163
|
+
return endpoint;
|
|
164
|
+
}
|
|
165
|
+
function scratchWorkspacePublication(workspace,publish) {
|
|
166
|
+
scratchCanonical(workspace);
|
|
167
|
+
const path=scratchPath.join(workspace,'.gestalt-scratch-lock');
|
|
168
|
+
let claimed=false;
|
|
169
|
+
for(let attempt=0;attempt<100;attempt++) {
|
|
170
|
+
try {scratchFs.mkdirSync(path,{mode:0o700});claimed=true;break;}
|
|
171
|
+
catch(error){if(error.code!=='EEXIST')throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10);}
|
|
172
|
+
}
|
|
173
|
+
if(!claimed)throw Error('SESSION_SCRATCH_BUSY');
|
|
174
|
+
scratchPrivate(path);
|
|
175
|
+
const fd=scratchFs.openSync(path,scratchFs.constants.O_RDONLY|scratchFs.constants.O_DIRECTORY|scratchFs.constants.O_NOFOLLOW);
|
|
176
|
+
const held=scratchFs.fstatSync(fd,{bigint:true});
|
|
177
|
+
try {
|
|
178
|
+
const parents=scratchManagedAncestors(workspace).map(ancestor=>ancestor.context.workspacePath);
|
|
179
|
+
scratchCheckParentPublications(workspace,parents);
|
|
180
|
+
const result=publish();
|
|
181
|
+
scratchCheckParentPublications(workspace,parents);
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
try {
|
|
186
|
+
const current=scratchFs.lstatSync(path,{bigint:true});
|
|
187
|
+
scratchAssert(current.isDirectory() && !current.isSymbolicLink() && current.dev===held.dev && current.ino===held.ino && current.birthtimeNs===held.birthtimeNs);
|
|
188
|
+
scratchFs.rmdirSync(path);
|
|
189
|
+
} finally {scratchFs.closeSync(fd);}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function scratchCheckParentPublications(workspace,logicalParents=[]) {
|
|
193
|
+
const parents=new Set(logicalParents);let current=scratchPath.parse(workspace).root;
|
|
194
|
+
for(const part of workspace.slice(current.length).split(scratchPath.sep).filter(Boolean)) {
|
|
195
|
+
current=scratchPath.join(current,part);if(part==='tmp')parents.add(scratchPath.dirname(current));
|
|
196
|
+
}
|
|
197
|
+
parents.delete(workspace);
|
|
198
|
+
for(const parent of parents) {
|
|
199
|
+
try{scratchFs.lstatSync(scratchPath.join(parent,'.gestalt-scratch-lock'));}
|
|
200
|
+
catch(error){if(error.code==='ENOENT')continue;throw error;}
|
|
201
|
+
throw Error('SESSION_SCRATCH_BUSY');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
131
204
|
function scratchContext(environment = process.env, allowReleased = false) {
|
|
132
205
|
if (!Object.hasOwn(environment, scratchVariable)) return null;
|
|
133
206
|
const context = JSON.parse(environment[scratchVariable]);
|
|
134
|
-
scratchAssert(context?.schemaVersion
|
|
207
|
+
scratchAssert([1,2].includes(context?.schemaVersion) && scratchId(context.ownerId));
|
|
135
208
|
scratchCanonical(context.workspacePath);
|
|
136
209
|
const container = scratchPath.join(context.workspacePath, 'tmp', 'sessions');
|
|
137
210
|
scratchAssert(context.directory === scratchPath.join(container, context.ownerId) &&
|
|
@@ -144,11 +217,15 @@ function scratchContext(environment = process.env, allowReleased = false) {
|
|
|
144
217
|
scratchAssert(!process.getuid || scratchFs.lstatSync(parent).uid === process.getuid());
|
|
145
218
|
for (const directory of [container, context.directory]) scratchPrivate(directory);
|
|
146
219
|
const marker = scratchJson(context.markerPath);
|
|
147
|
-
scratchAssert(marker?.schemaVersion ===
|
|
220
|
+
scratchAssert(marker?.schemaVersion === context.schemaVersion && marker.ownerId === context.ownerId &&
|
|
148
221
|
marker.workspacePath === context.workspacePath && scratchId(marker.sessionId) &&
|
|
149
222
|
typeof marker.createdAt === 'string' && Number.isFinite(Date.parse(marker.createdAt)) &&
|
|
150
223
|
Array.isArray(marker.providerThreads) && marker.providerThreads.every(thread =>
|
|
151
224
|
['codex', 'kimi'].includes(thread?.provider) && scratchId(thread.threadId)));
|
|
225
|
+
if(context.schemaVersion===2) {
|
|
226
|
+
scratchAssert(JSON.stringify(context.runtime)===JSON.stringify(marker.runtime));
|
|
227
|
+
scratchValidateRuntime(marker,marker.runtime);
|
|
228
|
+
} else scratchAssert(context.runtime===undefined && marker.runtime===undefined);
|
|
152
229
|
if (marker.ownerKind === 'mobile-session') {
|
|
153
230
|
scratchAssert(context.ownerId === 'mobile-' + scratchCrypto.createHash('sha256').update(marker.sessionId).digest('hex') &&
|
|
154
231
|
marker.authority?.kind === 'mobile-roster' && marker.authority.sessionId === marker.sessionId);
|
|
@@ -169,7 +246,8 @@ function scratchContext(environment = process.env, allowReleased = false) {
|
|
|
169
246
|
}
|
|
170
247
|
function scratchEnvironment(environment = process.env) {
|
|
171
248
|
const context = scratchContext(environment);
|
|
172
|
-
|
|
249
|
+
const directory=context && scratchTemporaryDirectory(context);
|
|
250
|
+
return context ? { ...environment, TMPDIR: directory, TMP: directory, TEMP: directory } : { ...environment };
|
|
173
251
|
}
|
|
174
252
|
function scratchDiscoveryEnvironment(environment = process.env) {
|
|
175
253
|
const result = { ...environment };
|
|
@@ -198,7 +276,10 @@ function scratchContainer(workspace) {
|
|
|
198
276
|
}
|
|
199
277
|
function scratchOwnerContext(workspace, ownerId) {
|
|
200
278
|
const directory = scratchPath.join(workspace, 'tmp', 'sessions', ownerId);
|
|
201
|
-
|
|
279
|
+
const context={schemaVersion:1,workspacePath:workspace,ownerId,directory,markerPath:scratchPath.join(directory,'.gestalt-owner.json')};
|
|
280
|
+
try {const marker=scratchJson(context.markerPath);if(marker.schemaVersion===2){context.schemaVersion=2;context.runtime=marker.runtime;}}
|
|
281
|
+
catch(error){if(error.code!=='ENOENT')throw error;}
|
|
282
|
+
return context;
|
|
202
283
|
}
|
|
203
284
|
function scratchLeaseRecords(context) {
|
|
204
285
|
const directory = scratchPath.join(context.directory, 'leases');
|
|
@@ -234,20 +315,34 @@ function scratchAncestorOwner(context) {
|
|
|
234
315
|
return {
|
|
235
316
|
context, identity: scratchDirectoryIdentity(context.directory),
|
|
236
317
|
provenance: JSON.stringify([marker.schemaVersion, marker.ownerKind, marker.ownerId, marker.workspacePath,
|
|
237
|
-
marker.sessionId, marker.createdAt, marker.authority.kind, marker.authority.sessionId ?? null, marker.authority.leaseId ?? null]),
|
|
318
|
+
marker.sessionId, marker.createdAt, marker.authority.kind, marker.authority.sessionId ?? null, marker.authority.leaseId ?? null, marker.runtime ?? null]),
|
|
238
319
|
};
|
|
239
320
|
}
|
|
240
|
-
function scratchManagedAncestors(workspace) {
|
|
321
|
+
function scratchManagedAncestors(workspace, ancestors=[], visiting=new Set()) {
|
|
322
|
+
scratchAssert(!visiting.has(workspace) && visiting.size<64);
|
|
323
|
+
visiting.add(workspace);
|
|
241
324
|
const parts = workspace.slice(scratchPath.parse(workspace).root.length).split(scratchPath.sep).filter(Boolean);
|
|
242
|
-
const
|
|
325
|
+
const runtimeBase=process.getuid?scratchRuntimeContainer():undefined;
|
|
243
326
|
let directory = scratchPath.parse(workspace).root;
|
|
244
327
|
for (let i = 0; i < parts.length; i++) {
|
|
245
328
|
directory = scratchPath.join(directory, parts[i]);
|
|
329
|
+
if(runtimeBase && scratchPath.dirname(directory)===runtimeBase) {
|
|
330
|
+
scratchPrivate(directory);
|
|
331
|
+
const locator=scratchJson(scratchPath.join(directory,'.gestalt-runtime.json'));
|
|
332
|
+
scratchAssert(typeof locator.workspacePath==='string' && scratchId(locator.ownerId));
|
|
333
|
+
const owner=scratchOwnerContext(locator.workspacePath,locator.ownerId);
|
|
334
|
+
scratchContext({[scratchVariable]:JSON.stringify(owner)},true);
|
|
335
|
+
scratchAssert(owner.runtime?.directory===directory);
|
|
336
|
+
scratchManagedAncestors(owner.directory,ancestors,visiting);
|
|
337
|
+
}
|
|
246
338
|
if (i >= 2 && parts[i - 1] === 'sessions' && parts[i - 2] === 'tmp') {
|
|
339
|
+
if(ancestors.some(ancestor=>ancestor.context.directory===directory))continue;
|
|
340
|
+
scratchAssert(ancestors.length<64);
|
|
247
341
|
const ownerWorkspace = scratchPath.dirname(scratchPath.dirname(scratchPath.dirname(directory)));
|
|
248
342
|
ancestors.push(scratchAncestorOwner(scratchOwnerContext(ownerWorkspace, parts[i])));
|
|
249
343
|
}
|
|
250
344
|
}
|
|
345
|
+
visiting.delete(workspace);
|
|
251
346
|
return ancestors;
|
|
252
347
|
}
|
|
253
348
|
function scratchRevalidateAncestor(ancestor) {
|
|
@@ -342,9 +437,38 @@ function scratchRecoverToolLeases(workspace, ownerId, token) {
|
|
|
342
437
|
{...lease, state: 'released', consumers: [], updatedAt: new Date().toISOString()});
|
|
343
438
|
}
|
|
344
439
|
}
|
|
440
|
+
// Offline-only publication recovery also works when allocation never reached an owner.
|
|
441
|
+
function scratchPublicationSnapshot(workspace) {
|
|
442
|
+
scratchCanonical(workspace);
|
|
443
|
+
const path=scratchPath.join(workspace,'.gestalt-scratch-lock');
|
|
444
|
+
scratchPrivate(path);
|
|
445
|
+
scratchAssert(scratchFs.readdirSync(path).length===0);
|
|
446
|
+
const expected=scratchDirectoryIdentity(path);
|
|
447
|
+
const token=scratchCrypto.createHash('sha256').update(JSON.stringify({
|
|
448
|
+
workspace:scratchDirectoryIdentity(workspace),lock:expected,
|
|
449
|
+
ancestors:scratchManagedAncestors(workspace).map(ancestor=>({
|
|
450
|
+
owner:ancestor.provenance,identity:ancestor.identity,
|
|
451
|
+
leases:scratchFs.existsSync(scratchPath.join(ancestor.context.directory,'leases'))
|
|
452
|
+
? scratchLeaseRecords(ancestor.context).sort((a,b)=>a.leaseId.localeCompare(b.leaseId)):[],
|
|
453
|
+
})),
|
|
454
|
+
},(_,value)=>typeof value==='bigint'?value.toString():value)).digest('hex');
|
|
455
|
+
return {path,expected,token};
|
|
456
|
+
}
|
|
457
|
+
function scratchRecoverPublication(workspace,token) {
|
|
458
|
+
scratchAssert(typeof token==='string' && /^[a-f0-9]{64}$/.test(token));
|
|
459
|
+
const snapshot=scratchPublicationSnapshot(workspace);
|
|
460
|
+
if(snapshot.token!==token)throw Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
|
|
461
|
+
const fd=scratchFs.openSync(snapshot.path,scratchFs.constants.O_RDONLY|scratchFs.constants.O_DIRECTORY|scratchFs.constants.O_NOFOLLOW);
|
|
462
|
+
try {
|
|
463
|
+
const held=scratchFs.fstatSync(fd,{bigint:true});
|
|
464
|
+
scratchAssert(scratchSameDirectory(snapshot.expected,{dev:held.dev,ino:held.ino,birth:held.birthtimeNs}));
|
|
465
|
+
if(scratchPublicationSnapshot(workspace).token!==token)throw Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
|
|
466
|
+
scratchFs.rmdirSync(snapshot.path);
|
|
467
|
+
} finally {scratchFs.closeSync(fd);}
|
|
468
|
+
}
|
|
345
469
|
function scratchRecoveryCommand(args) {
|
|
346
470
|
const [action, ...options] = args;
|
|
347
|
-
scratchAssert(['inspect', 'recover', 'inspect-tool-leases', 'recover-tool-leases'].includes(action));
|
|
471
|
+
scratchAssert(['inspect', 'recover', 'inspect-tool-leases', 'recover-tool-leases', 'inspect-publication', 'recover-publication'].includes(action));
|
|
348
472
|
const values = {};
|
|
349
473
|
let confirmed = false;
|
|
350
474
|
for (let index = 0; index < options.length; index++) {
|
|
@@ -354,7 +478,18 @@ function scratchRecoveryCommand(args) {
|
|
|
354
478
|
scratchAssert(typeof options[index + 1] === 'string' && !options[index + 1].startsWith('--'));
|
|
355
479
|
values[name] = options[++index];
|
|
356
480
|
}
|
|
357
|
-
scratchAssert(values['--cwd'] && values['--owner']);
|
|
481
|
+
scratchAssert(values['--cwd'] && (action.endsWith('-publication') ? !values['--owner'] : values['--owner']));
|
|
482
|
+
if(action.endsWith('-publication')) {
|
|
483
|
+
if(action==='inspect-publication') {
|
|
484
|
+
scratchAssert(!confirmed && !values['--expect']);
|
|
485
|
+
process.stdout.write(JSON.stringify({schemaVersion:1,status:'confirmationRequired',token:scratchPublicationSnapshot(values['--cwd']).token})+'\n');
|
|
486
|
+
} else {
|
|
487
|
+
scratchAssert(confirmed && values['--expect']);
|
|
488
|
+
scratchRecoverPublication(values['--cwd'],values['--expect']);
|
|
489
|
+
process.stdout.write(JSON.stringify({schemaVersion:1,status:'recovered'})+'\n');
|
|
490
|
+
}
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
358
493
|
if (action === 'inspect' || action === 'inspect-tool-leases') {
|
|
359
494
|
scratchAssert(!confirmed && !values['--expect']);
|
|
360
495
|
const snapshot = action === 'inspect' ? scratchContainmentSnapshot(values['--cwd'], values['--owner'])
|
|
@@ -369,6 +504,7 @@ function scratchRecoveryCommand(args) {
|
|
|
369
504
|
}
|
|
370
505
|
}
|
|
371
506
|
function scratchWithContainment(workspace, publish) {
|
|
507
|
+
return scratchWorkspacePublication(workspace,()=>{
|
|
372
508
|
scratchCanonical(workspace);
|
|
373
509
|
const selected = scratchDirectoryIdentity(workspace), ancestors = scratchManagedAncestors(workspace), claims = [];
|
|
374
510
|
try {
|
|
@@ -411,6 +547,7 @@ function scratchWithContainment(workspace, publish) {
|
|
|
411
547
|
}
|
|
412
548
|
if (failure) throw failure;
|
|
413
549
|
}
|
|
550
|
+
});
|
|
414
551
|
}
|
|
415
552
|
function scratchAllocate(workspace,kind,consumer) {
|
|
416
553
|
scratchAssert(['cli-session','workspace-service'].includes(kind)&&scratchId(consumer));
|
|
@@ -423,6 +560,10 @@ function scratchAllocate(workspace,kind,consumer) {
|
|
|
423
560
|
const leaseId=scratchCrypto.randomUUID(),time=new Date().toISOString();
|
|
424
561
|
const lease={schemaVersion:1,ownerId,workspacePath:workspace,leaseId,state:'active',processIdentity:scratchCrypto.randomUUID(),createdAt:time,updatedAt:time,consumers:[consumer]};
|
|
425
562
|
const marker={schemaVersion:1,ownerKind:kind,ownerId,workspacePath:workspace,sessionId:ownerId,createdAt:time,authority:{kind:'lease',leaseId},providerThreads:[]};
|
|
563
|
+
if(process.platform!=='win32') {
|
|
564
|
+
marker.schemaVersion=2;marker.runtime=scratchAllocateRuntime(marker);
|
|
565
|
+
context.schemaVersion=2;context.runtime=marker.runtime;
|
|
566
|
+
}
|
|
426
567
|
scratchPublish(scratchPath.join(context.directory,'leases',leaseId+'.json'),lease,true);scratchPublish(context.markerPath,marker,true);
|
|
427
568
|
scratchContext({[scratchVariable]:JSON.stringify(context)});return {context,lease,lock};
|
|
428
569
|
});
|
|
@@ -446,6 +587,7 @@ function scratchRelease(ownership) {
|
|
|
446
587
|
});
|
|
447
588
|
}
|
|
448
589
|
function scratchMetadata(context, operation, waitMs = 0) {
|
|
590
|
+
return scratchWorkspacePublication(context.workspacePath,()=>{
|
|
449
591
|
scratchContext({[scratchVariable]: JSON.stringify(context)});
|
|
450
592
|
const mobile = scratchJson(context.markerPath).ownerKind === 'mobile-session';
|
|
451
593
|
// Mobile cleanup/association use this same controller fence. CLI/service
|
|
@@ -466,6 +608,7 @@ function scratchMetadata(context, operation, waitMs = 0) {
|
|
|
466
608
|
if (mobile) scratchAssert(!scratchFs.existsSync(scratchPath.join(context.directory, '.association-lock')));
|
|
467
609
|
return operation();
|
|
468
610
|
} finally {scratchFs.rmdirSync(lock);}
|
|
611
|
+
});
|
|
469
612
|
}
|
|
470
613
|
function scratchBorrow(context, consumer) {
|
|
471
614
|
scratchAssert(scratchId(consumer));
|
|
@@ -642,7 +785,7 @@ async function scratchCli(manager, args) {
|
|
|
642
785
|
}
|
|
643
786
|
// END SESSION SCRATCH RUNTIME
|
|
644
787
|
if (process.argv[1] === 'validate') {
|
|
645
|
-
try {const context = scratchContext(); process.stdout.write(scratchJson(context.markerPath).ownerKind + '\n' + context
|
|
788
|
+
try {const context = scratchContext(); process.stdout.write(scratchJson(context.markerPath).ownerKind + '\n' + scratchTemporaryDirectory(context));}
|
|
646
789
|
catch { process.stderr.write('gestalt: invalid managed session temporary context\n'); process.exitCode = 1; }
|
|
647
790
|
}
|
|
648
791
|
if (process.argv[1] === 'scratch') {
|
|
@@ -673,7 +816,6 @@ validate_session_tmp_context() {
|
|
|
673
816
|
local session_directory validated
|
|
674
817
|
validated=$(node -e "$(session_scratch_runtime)" validate) ||
|
|
675
818
|
die 'managed session temporary context rejected'
|
|
676
|
-
session_tmp_owner_kind=${validated%%$'\n'*}
|
|
677
819
|
session_directory=${validated#*$'\n'}
|
|
678
820
|
export TMPDIR="$session_directory" TMP="$session_directory" TEMP="$session_directory"
|
|
679
821
|
fi
|
|
@@ -709,34 +851,23 @@ Commands:
|
|
|
709
851
|
serena doctor [--cwd ROOT] Check install, sandbox, MCP tools and optional language readiness.
|
|
710
852
|
serena index --cwd ROOT Explicit native symbol/cache warmup for one project.
|
|
711
853
|
serena mcp --cwd ROOT Confined workspace MCP; always Codex context and editing mode.
|
|
712
|
-
xerj install Install the checksum-verified managed xerj release.
|
|
713
|
-
xerj update [VERSION] Install an official release (default: latest).
|
|
714
|
-
xerj test [--json] Test installed XERJ in disposable storage; never real indexes.
|
|
715
|
-
xerj [args...] Run xerj with managed installation and state paths.
|
|
716
|
-
xerj autoindex --cwd DIR Index a source root; add --watch for continuous updates.
|
|
717
|
-
xerj mcp [args...] Native MCP stdio proxy to a loopback HTTP node.
|
|
718
|
-
xerj probe Read-only JSON readiness (5-second default deadline).
|
|
719
|
-
xerj ensure-ready Reuse or start a shared authenticated local backend.
|
|
720
|
-
xerj status Read-only readiness and lifecycle ownership JSON.
|
|
721
|
-
xerj stop Stop only a backend owned by this manager.
|
|
722
854
|
path [NAME|--json] Print managed executable and runtime paths.
|
|
723
855
|
skills install, update Maintain the optional Dyne.org skill collection only.
|
|
724
856
|
skills status [--json] Read installed version, revision and integrity.
|
|
725
857
|
skills-export [ARCHIVE] Export installed skills and skill profiles.
|
|
726
858
|
skills-import ARCHIVE Import a skills archive into this installation.
|
|
727
|
-
doctor [--cwd ROOT] Check prerequisites
|
|
859
|
+
doctor [--cwd ROOT] Check prerequisites and installation.
|
|
728
860
|
version Print manager and detected component versions.
|
|
729
861
|
help Show this help.
|
|
730
862
|
|
|
731
863
|
Update components (also accepted as --component COMPONENT):
|
|
732
|
-
all Gestalt core plus installed Serena
|
|
864
|
+
all Gestalt core plus installed Serena and Playwright (default).
|
|
733
865
|
gestalt Manager, Agents, Mobile, and context-mode runtime.
|
|
734
866
|
serena Latest stable Serena and its private uv/Python tooling.
|
|
735
|
-
xerj Latest official managed XERJ release.
|
|
736
867
|
playwright Stable Playwright MCP package; Chrome is externally maintained.
|
|
737
868
|
|
|
738
869
|
Optional components absent from this installation are skipped by 'all'.
|
|
739
|
-
Selecting serena
|
|
870
|
+
Selecting serena or playwright explicitly installs or updates that component only.
|
|
740
871
|
--extra-skills applies only to all or gestalt; it adds curated third-party skills.
|
|
741
872
|
Node, npm, Codex, Kimi, and system language servers are externally maintained.
|
|
742
873
|
|
|
@@ -749,1150 +880,25 @@ Environment:
|
|
|
749
880
|
GESTALT_MOBILE_VERSION npm version or tag (default: latest).
|
|
750
881
|
GESTALT_SKILLS_SOURCE Collection source override (always unverified).
|
|
751
882
|
GESTALT_SKILLS_REF Collection Git ref or immutable revision (default: main).
|
|
752
|
-
XERJ_INSTALL_DIR Must equal $GESTALT_HOME/xerj when set.
|
|
753
|
-
XERJ_READY_TIMEOUT_MS Overall readiness deadline (default: 5000).
|
|
754
883
|
EOF
|
|
755
884
|
}
|
|
756
885
|
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
local pattern='^http://(127\.0\.0\.1|localhost|\[::1\])(:([0-9]{1,5}))?/?$'
|
|
760
|
-
[[ $url =~ $pattern ]] || die 'managed xerj URLs must be loopback HTTP with no credentials, path, query or fragment'
|
|
761
|
-
port=${BASH_REMATCH[3]:-80}
|
|
762
|
-
((10#$port >= 1 && 10#$port <= 65535)) || die 'xerj URL port must be between 1 and 65535'
|
|
763
|
-
validated_xerj_url=${url/http:\/\/localhost/http:\/\/127.0.0.1}
|
|
764
|
-
validated_xerj_port=$port
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
validate_xerj_bind() {
|
|
768
|
-
case $1 in
|
|
769
|
-
127.0.0.1 | ::1) ;;
|
|
770
|
-
*) die 'managed xerj server bind must be 127.0.0.1 or ::1' ;;
|
|
771
|
-
esac
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
# Reject lexical escapes and existing links before allocating any xerj paths.
|
|
775
|
-
# This is path validation, not a filesystem sandbox against concurrent changes.
|
|
776
|
-
validate_xerj_path() {
|
|
886
|
+
# Reject lexical escapes and link traversal before allocating managed tooling.
|
|
887
|
+
validate_managed_tree_path() {
|
|
777
888
|
local candidate=$1 part current=''
|
|
778
889
|
local -a components=()
|
|
779
890
|
[[ $candidate == /* && ! $candidate =~ [[:cntrl:]] ]] ||
|
|
780
|
-
die '
|
|
781
|
-
[[ $candidate != */ && $candidate != *//* ]] || die '
|
|
891
|
+
die 'managed paths must be absolute and contain no control characters'
|
|
892
|
+
[[ $candidate != */ && $candidate != *//* ]] || die 'managed paths must be normalized'
|
|
782
893
|
IFS='/' read -r -a components <<< "$candidate"
|
|
783
894
|
for part in "${components[@]}"; do
|
|
784
895
|
[[ -n $part ]] || continue
|
|
785
|
-
[[ $part != . && $part != .. ]] || die '
|
|
896
|
+
[[ $part != . && $part != .. ]] || die 'managed paths cannot contain . or ..'
|
|
786
897
|
current=$current/$part
|
|
787
|
-
[[ ! -L $current ]] || die "
|
|
788
|
-
done
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
canonical_xerj_root() {
|
|
792
|
-
# Resolve selected home aliases; managed descendants must remain link-free.
|
|
793
|
-
local ancestor=$1 suffix='' component
|
|
794
|
-
[[ $ancestor == /* && $ancestor != */ && $ancestor != *//* && ! $ancestor =~ [[:cntrl:]] ]] ||
|
|
795
|
-
die 'xerj home must be an absolute normalized path'
|
|
796
|
-
case /$ancestor/ in */./* | */../*) die 'xerj home cannot contain . or ..' ;; esac
|
|
797
|
-
while [[ ! -d $ancestor ]]; do
|
|
798
|
-
[[ ! -e $ancestor && ! -L $ancestor ]] || die 'GESTALT_HOME ancestor is not a directory'
|
|
799
|
-
component=${ancestor##*/}
|
|
800
|
-
suffix=/$component$suffix
|
|
801
|
-
ancestor=${ancestor%/*}
|
|
802
|
-
[[ -n $ancestor ]] || ancestor=/
|
|
803
|
-
done
|
|
804
|
-
ancestor=$(CDPATH='' cd -- "$ancestor" && pwd -P)
|
|
805
|
-
printf '%s\n' "${ancestor%/}$suffix"
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
load_xerj_paths() {
|
|
809
|
-
gestalt_home=$(canonical_xerj_root "$gestalt_home")
|
|
810
|
-
codex_home=$(canonical_xerj_root "$codex_home")
|
|
811
|
-
validate_managed_path GESTALT_HOME "$gestalt_home"
|
|
812
|
-
xerj_root=$gestalt_home/xerj
|
|
813
|
-
xerj_data=$codex_home/xerj-data
|
|
814
|
-
xerj_autoindex_home=${GESTALT_XERJ_AUTO_INDEX_HOME:-$xerj_data/autoindex}
|
|
815
|
-
xerj_bin=$xerj_root/xerj
|
|
816
|
-
validate_xerj_path "$xerj_root"
|
|
817
|
-
validate_xerj_path "$xerj_data"
|
|
818
|
-
validate_xerj_path "$xerj_autoindex_home"
|
|
819
|
-
[[ ! -e $xerj_bin || -f $xerj_bin ]] || die 'managed xerj executable must be a regular file'
|
|
820
|
-
[[ ${XERJ_INSTALL_DIR:-$xerj_root} == "$xerj_root" ]] ||
|
|
821
|
-
die 'XERJ_INSTALL_DIR conflicts with the managed xerj installation'
|
|
822
|
-
[[ -z ${XERJ_REPO:-} || ${XERJ_REPO:-} == xerj-org/xerj ]] ||
|
|
823
|
-
die 'managed xerj uses the official release repository'
|
|
824
|
-
[[ ${XERJ_INSECURE_SKIP_CHECKSUM:-0} == 0 ]] || die 'xerj checksum verification is required'
|
|
825
|
-
local directory link
|
|
826
|
-
for directory in "$xerj_root" "$xerj_data" "$xerj_autoindex_home"; do
|
|
827
|
-
if [[ -d $directory ]]; then
|
|
828
|
-
# Segment compaction removes files while clients start. Ignore only
|
|
829
|
-
# ENOENT races, retaining the same link checks on every existing entry.
|
|
830
|
-
require_command node
|
|
831
|
-
link=$(node - "$directory" "$xerj_data" <<'NODE'
|
|
832
|
-
const { lstatSync, readdirSync } = require('node:fs');
|
|
833
|
-
const { join, relative } = require('node:path');
|
|
834
|
-
// Autoindex reuses immutable blobs and prepared documents across generations.
|
|
835
|
-
// Keep the link ban on credentials, configuration, executables and metadata.
|
|
836
|
-
const snapshotContent = path => /^autoindex\/[^/]+\/sync-snapshots\/[^/]+\/(blobs|prepared)\/[^/]+$/.test(relative(process.argv[3], path));
|
|
837
|
-
function visit(path) {
|
|
838
|
-
try {
|
|
839
|
-
const info = lstatSync(path);
|
|
840
|
-
if (info.isSymbolicLink() || (info.isFile() && info.nlink > 1 && !snapshotContent(path))) return path;
|
|
841
|
-
if (info.isDirectory()) for (const name of readdirSync(path)) {
|
|
842
|
-
const found = visit(join(path, name));
|
|
843
|
-
if (found) return found;
|
|
844
|
-
}
|
|
845
|
-
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
846
|
-
}
|
|
847
|
-
process.stdout.write(visit(process.argv[2]) ?? '');
|
|
848
|
-
NODE
|
|
849
|
-
)
|
|
850
|
-
[[ -z $link ]] || die "managed xerj tree contains a symbolic or hard link: $link"
|
|
851
|
-
fi
|
|
852
|
-
done
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
install_xerj() {
|
|
856
|
-
local version=$1
|
|
857
|
-
local os cpu target stage asset expected actual member listing
|
|
858
|
-
require_command curl
|
|
859
|
-
require_command tar
|
|
860
|
-
require_command mktemp
|
|
861
|
-
unset TAR_OPTIONS GZIP
|
|
862
|
-
trap 'exit 130' INT
|
|
863
|
-
trap 'exit 143' TERM
|
|
864
|
-
os=$(uname -s)
|
|
865
|
-
cpu=$(uname -m)
|
|
866
|
-
case $cpu in
|
|
867
|
-
x86_64 | amd64) cpu=x86_64 ;;
|
|
868
|
-
aarch64 | arm64) cpu=aarch64 ;;
|
|
869
|
-
*) die "unsupported xerj CPU: $cpu" ;;
|
|
870
|
-
esac
|
|
871
|
-
case $os in
|
|
872
|
-
Linux) target=$cpu-unknown-linux-musl ;;
|
|
873
|
-
Darwin) target=$cpu-apple-darwin ;;
|
|
874
|
-
*) die "managed xerj supports Linux and macOS, not $os" ;;
|
|
875
|
-
esac
|
|
876
|
-
[[ -z ${XERJ_LIBC:-} || ${XERJ_LIBC:-} == musl || $os == Darwin ]] ||
|
|
877
|
-
die 'managed Linux xerj uses the audited static musl release'
|
|
878
|
-
umask 077
|
|
879
|
-
mkdir -p -- "$xerj_root"
|
|
880
|
-
xerj_install_scratch=$(mktemp -d "$xerj_root/.install.XXXXXXXX")
|
|
881
|
-
stage=xerj-$version-$target
|
|
882
|
-
asset=$stage.tar.gz
|
|
883
|
-
local base=https://github.com/xerj-org/xerj/releases/download/v$version
|
|
884
|
-
# -q disables ~/.curlrc; all downloads and extraction output stay in scratch.
|
|
885
|
-
curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
|
|
886
|
-
--connect-timeout 20 --max-time 120 "$base/$asset" --output "$xerj_install_scratch/release.tar.gz"
|
|
887
|
-
curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
|
|
888
|
-
--connect-timeout 20 --max-time 120 "$base/$asset.sha256" --output "$xerj_install_scratch/release.sha256"
|
|
889
|
-
IFS=' ' read -r expected _ < "$xerj_install_scratch/release.sha256" || die 'missing xerj checksum'
|
|
890
|
-
[[ $expected =~ ^[[:xdigit:]]{64}$ ]] || die 'invalid xerj checksum'
|
|
891
|
-
actual=$(calculate_sha256 "$xerj_install_scratch/release.tar.gz")
|
|
892
|
-
actual=${actual%% *}
|
|
893
|
-
actual=$(printf '%s' "$actual" | tr 'A-F' 'a-f')
|
|
894
|
-
expected=$(printf '%s' "$expected" | tr 'A-F' 'a-f')
|
|
895
|
-
[[ $actual == "$expected" ]] || die 'xerj checksum mismatch; prior binary preserved'
|
|
896
|
-
member=$stage/xerj
|
|
897
|
-
listing=$(tar -tzf "$xerj_install_scratch/release.tar.gz")
|
|
898
|
-
[[ $(printf '%s\n' "$listing" | grep -Fxc "$member") == 1 ]] ||
|
|
899
|
-
die 'xerj archive must contain exactly one expected binary'
|
|
900
|
-
listing=$(tar -tvzf "$xerj_install_scratch/release.tar.gz" "$member")
|
|
901
|
-
[[ $listing == -* ]] || die 'xerj archive binary must be a regular file'
|
|
902
|
-
# Stream only that regular member. Never unpack archive paths or links.
|
|
903
|
-
tar -xOzf "$xerj_install_scratch/release.tar.gz" "$member" > "$xerj_install_scratch/xerj"
|
|
904
|
-
[[ -s $xerj_install_scratch/xerj ]] || die 'empty xerj binary'
|
|
905
|
-
chmod 0755 "$xerj_install_scratch/xerj"
|
|
906
|
-
if (($# > 0)); then
|
|
907
|
-
require_command node
|
|
908
|
-
node - "$xerj_install_scratch/xerj" "$version" <<'JS'
|
|
909
|
-
const { spawnSync } = require('node:child_process');
|
|
910
|
-
const result = spawnSync(process.argv[2], ['-V'], { timeout: 5000, maxBuffer: 65536,
|
|
911
|
-
encoding: 'utf8', env: { PATH: process.env.PATH, XERJ_INSTALL_DIR: require('node:path').dirname(process.argv[2]) } });
|
|
912
|
-
const found = result.stdout?.match(/\b(?:v)?(\d+\.\d+\.\d+(?:-[\w.-]+)?)\b/);
|
|
913
|
-
if (result.error || result.status !== 0 || found?.[1] !== process.argv[3]) {
|
|
914
|
-
console.error('downloaded xerj version does not match requested release; prior binary preserved');
|
|
915
|
-
process.exit(1);
|
|
916
|
-
}
|
|
917
|
-
JS
|
|
918
|
-
fi
|
|
919
|
-
mv -f -- "$xerj_install_scratch/xerj" "$xerj_bin"
|
|
920
|
-
log "installed xerj $version at $xerj_bin"
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
update_xerj() {
|
|
924
|
-
(($# <= 1)) || die 'usage: gestalt xerj update [VERSION]'
|
|
925
|
-
local version=${1:-latest}
|
|
926
|
-
if [[ $version == latest ]]; then
|
|
927
|
-
require_command curl
|
|
928
|
-
require_command node
|
|
929
|
-
version=$(curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
|
|
930
|
-
--connect-timeout 20 --max-time 30 https://api.github.com/repos/xerj-org/xerj/releases/latest |
|
|
931
|
-
node -e 'let s=""; process.stdin.on("data", b => s+=b); process.stdin.on("end", () => { const r=JSON.parse(s); if(r.draft || typeof r.tag_name!=="string") process.exit(1); process.stdout.write(r.tag_name); });')
|
|
932
|
-
fi
|
|
933
|
-
version=${version#v}
|
|
934
|
-
[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+([.-][a-zA-Z0-9]+)*)?$ ]] || die 'invalid xerj release version'
|
|
935
|
-
install_xerj "$version"
|
|
936
|
-
log 'run gestalt xerj test to check upstream regressions; existing servers and indexes were not changed'
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
# Embedded because the distributed manager is one self-contained executable.
|
|
940
|
-
# Exercise the native binary, not the wrapper's compensating watcher lock.
|
|
941
|
-
test_xerj() {
|
|
942
|
-
(($# == 0)) || { (($# == 1)) && [[ $1 == --json ]]; } || die 'usage: gestalt xerj test [--json]'
|
|
943
|
-
require_command node
|
|
944
|
-
require_command git
|
|
945
|
-
[[ -x $xerj_bin ]] || die "xerj is not installed; run 'gestalt xerj install'"
|
|
946
|
-
exec node --input-type=module - "$xerj_bin" "${1:-}" <<'JS'
|
|
947
|
-
import { spawn } from 'node:child_process';
|
|
948
|
-
import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
|
949
|
-
import { tmpdir } from 'node:os';
|
|
950
|
-
import { join } from 'node:path';
|
|
951
|
-
import net from 'node:net';
|
|
952
|
-
const binary = process.argv[2], json = process.argv[3] === '--json';
|
|
953
|
-
const directory = await mkdtemp(join(tmpdir(), 'gestalt-xerj-regression-'));
|
|
954
|
-
const rows = [], children = new Set();
|
|
955
|
-
let version = 'unknown', endpoint, authorization, interrupted = false;
|
|
956
|
-
const env = { PATH: process.env.PATH, HOME: join(directory, 'home'),
|
|
957
|
-
XDG_CACHE_HOME: join(directory, 'cache'), XDG_CONFIG_HOME: join(directory, 'config'),
|
|
958
|
-
XDG_DATA_HOME: join(directory, 'data'), TMPDIR: directory,
|
|
959
|
-
XERJ_INSTALL_DIR: join(binary, '..'), XERJ_CODE_HOME: join(directory, 'code'),
|
|
960
|
-
HF_HOME: join(directory, 'cache', 'huggingface'), XERJ_DISABLE_FEEDBACK: 'true',
|
|
961
|
-
GIT_CONFIG_NOSYSTEM: '1', LANG: 'C' };
|
|
962
|
-
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
963
|
-
function launch(command, args, timeout = 60000) {
|
|
964
|
-
const child = spawn(command, args, { cwd: directory, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
965
|
-
children.add(child);
|
|
966
|
-
const state = { child, stdout: '', stderr: '', code: null, ended: false, timedOut: false };
|
|
967
|
-
for (const stream of ['stdout', 'stderr']) child[stream].on('data', chunk => {
|
|
968
|
-
state[stream] = (state[stream] + chunk.toString()).slice(-262144);
|
|
969
|
-
});
|
|
970
|
-
const timer = timeout ? setTimeout(() => { state.timedOut = true; child.kill('SIGKILL'); }, timeout) : null;
|
|
971
|
-
state.done = new Promise(resolve => {
|
|
972
|
-
child.once('error', () => { state.spawnError = true; });
|
|
973
|
-
child.once('close', code => {
|
|
974
|
-
clearTimeout(timer); children.delete(child); state.code = code; state.ended = true; resolve(state);
|
|
975
|
-
});
|
|
976
|
-
});
|
|
977
|
-
return state;
|
|
978
|
-
}
|
|
979
|
-
async function stop(state) {
|
|
980
|
-
if (state.ended) return;
|
|
981
|
-
state.child.kill('SIGTERM');
|
|
982
|
-
const timer = setTimeout(() => state.child.kill('SIGKILL'), 2000);
|
|
983
|
-
await state.done; clearTimeout(timer);
|
|
984
|
-
}
|
|
985
|
-
async function until(predicate, ms = 30000) {
|
|
986
|
-
const expires = Date.now() + ms;
|
|
987
|
-
while (Date.now() < expires && !interrupted) {
|
|
988
|
-
if (await predicate()) return true;
|
|
989
|
-
await pause(100);
|
|
990
|
-
}
|
|
991
|
-
return false;
|
|
992
|
-
}
|
|
993
|
-
function record(name, pass, detail, issue) {
|
|
994
|
-
const row = { name, status: pass ? 'pass' : 'fail', detail, ...(issue ? { issue } : {}) };
|
|
995
|
-
rows.push(row);
|
|
996
|
-
if (!json) console.log(`${pass ? 'PASS' : 'FAIL'} ${name}: ${detail}${issue ? ` (#${issue})` : ''}`);
|
|
997
|
-
return pass;
|
|
998
|
-
}
|
|
999
|
-
function requirePass(name, pass, detail) {
|
|
1000
|
-
if (!record(name, pass, detail)) throw new Error(`${name} failed; dependent checks were not run`);
|
|
1001
|
-
}
|
|
1002
|
-
async function request(path, body) {
|
|
1003
|
-
const response = await fetch(endpoint + path, { signal: AbortSignal.timeout(5000),
|
|
1004
|
-
headers: { Authorization: authorization, 'Content-Type': 'application/json' },
|
|
1005
|
-
...(body ? { method: 'POST', body: JSON.stringify(body) } : {}) });
|
|
1006
|
-
if (!response.ok) throw new Error(`test backend HTTP ${response.status}`);
|
|
1007
|
-
return response.json();
|
|
1008
|
-
}
|
|
1009
|
-
async function hits(prefix) {
|
|
1010
|
-
return (await request(`/${prefix}-*/_search`, { size: 1000, query: { match_all: {} } })).hits.hits;
|
|
1011
|
-
}
|
|
1012
|
-
const paths = entries => entries.flatMap(hit => hit._source.ax_paths ?? [hit._source.ax_path]).filter(Boolean);
|
|
1013
|
-
async function contains(prefix, wanted, absent = []) {
|
|
1014
|
-
return until(async () => {
|
|
1015
|
-
const found = paths(await hits(prefix));
|
|
1016
|
-
return wanted.every(path => found.includes(path)) && absent.every(path => !found.includes(path));
|
|
1017
|
-
}, 10000);
|
|
1018
|
-
}
|
|
1019
|
-
const content = ['--no-graph', '--no-semantic', '--yes', '--workers', '2', '--pdf-workers', '1',
|
|
1020
|
-
'--bulk-mb', '4', '--max-file-gb', '1', '--progress', 'json'];
|
|
1021
|
-
function args(root, prefix, extra = []) {
|
|
1022
|
-
return ['autoindex', root, '--url', endpoint, '--prefix', prefix,
|
|
1023
|
-
'--state-dir', join(directory, 'journals', prefix), ...content, ...extra];
|
|
1024
|
-
}
|
|
1025
|
-
const index = (root, prefix, extra = []) => launch(binary, args(root, prefix, extra)).done;
|
|
1026
|
-
const succeeded = result => result.code === 0 && !result.timedOut && !result.spawnError;
|
|
1027
|
-
const successfulPass = output => output.split('\n').some(line => {
|
|
1028
|
-
try { const value = JSON.parse(line); return value.event === 'done' && value.ok === true; } catch { return false; }
|
|
1029
|
-
});
|
|
1030
|
-
async function git(root) {
|
|
1031
|
-
await mkdir(root, { recursive: true });
|
|
1032
|
-
if (!succeeded(await launch('git', ['init', '--quiet', root]).done)) throw new Error('fixture git init failed');
|
|
1033
|
-
}
|
|
1034
|
-
const onSignal = () => {
|
|
1035
|
-
interrupted = true;
|
|
1036
|
-
for (const child of children) child.kill('SIGTERM');
|
|
1037
|
-
setTimeout(() => { for (const child of children) child.kill('SIGKILL'); }, 2000).unref();
|
|
1038
|
-
};
|
|
1039
|
-
process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
|
|
1040
|
-
// A bounded whole-run deadline also covers watch processes and setup errors.
|
|
1041
|
-
const deadline = setTimeout(onSignal, 240000);
|
|
1042
|
-
try {
|
|
1043
|
-
await mkdir(env.HOME);
|
|
1044
|
-
const detected = await launch(binary, ['-V'], 5000).done;
|
|
1045
|
-
const match = detected.stdout.match(/\b(?:v)?(\d+\.\d+\.\d+(?:-[\w.-]+)?)\b/);
|
|
1046
|
-
if (!succeeded(detected) || !match) throw new Error('cannot read installed XERJ version');
|
|
1047
|
-
version = match[1];
|
|
1048
|
-
if (!json) console.log(`Testing XERJ ${version}; disposable source, backend and journals; no real indexes.`);
|
|
1049
|
-
const listener = net.createServer();
|
|
1050
|
-
await new Promise((resolve, reject) => { listener.once('error', reject); listener.listen(0, '127.0.0.1', resolve); });
|
|
1051
|
-
const port = listener.address().port;
|
|
1052
|
-
await new Promise(resolve => listener.close(resolve));
|
|
1053
|
-
endpoint = `http://127.0.0.1:${port}`;
|
|
1054
|
-
const data = join(directory, 'server');
|
|
1055
|
-
const config = join(directory, 'xerj.toml');
|
|
1056
|
-
await writeFile(config, `[embedding]\nmodel_cache_dir = ${JSON.stringify(join(directory, 'cache', 'models'))}\n[tls]\ncert_path = ${JSON.stringify(join(directory, 'cert.pem'))}\nkey_path = ${JSON.stringify(join(directory, 'key.pem'))}\n`);
|
|
1057
|
-
const serverArgs = ['--config', config, '--data-dir', data, '--bind', '127.0.0.1', '--port', String(port), '--embed-mode', 'lexical'];
|
|
1058
|
-
let server = launch(binary, serverArgs, 0);
|
|
1059
|
-
async function ready() {
|
|
1060
|
-
return until(async () => {
|
|
1061
|
-
if (server.ended) throw new Error('test backend exited before readiness');
|
|
1062
|
-
try {
|
|
1063
|
-
const key = (await readFile(join(data, 'admin.key'), 'utf8')).trim();
|
|
1064
|
-
authorization = `ApiKey ${key}`; env.XERJ_API_KEY = key;
|
|
1065
|
-
const health = await request('/_cluster/health');
|
|
1066
|
-
return health.cluster_name === 'xerj' && ['green', 'yellow'].includes(health.status);
|
|
1067
|
-
} catch { return false; }
|
|
1068
|
-
}, 20000);
|
|
1069
|
-
}
|
|
1070
|
-
requirePass('backend', await ready(), 'authenticated temporary loopback backend');
|
|
1071
|
-
const multi = join(directory, 'repositories');
|
|
1072
|
-
for (const name of ['bitcoin-core', 'bitcoin-knots', 'bitcoin-roots']) {
|
|
1073
|
-
const root = join(multi, name); await git(root);
|
|
1074
|
-
await writeFile(join(root, 'shared.ts'), 'export function sharedFork() { return "same implementation"; }\n');
|
|
1075
|
-
await writeFile(join(root, 'unique.ts'), `export const repository = "${name}";\n`);
|
|
1076
|
-
}
|
|
1077
|
-
await writeFile(join(multi, '.xerjignore'), 'node_modules/\nsecrets/\n!vendor/\n');
|
|
1078
|
-
for (const tree of ['node_modules', 'secrets', 'vendor', '.hidden']) {
|
|
1079
|
-
await mkdir(join(multi, tree)); await writeFile(join(multi, tree, 'fixture.ts'), `export const location = "${tree}";\n`);
|
|
1080
|
-
}
|
|
1081
|
-
await writeFile(join(multi, 'bitcoin-core', '.gitignore'), 'ignored.ts\n');
|
|
1082
|
-
await writeFile(join(multi, 'bitcoin-core', 'ignored.ts'), 'export const ignored = true;\n');
|
|
1083
|
-
requirePass('initial-index', succeeded(await index(multi, 'multi')), 'multi-repository initial generation');
|
|
1084
|
-
requirePass('repository-identity', await contains('multi', ['bitcoin-core/shared.ts', 'bitcoin-knots/shared.ts', 'bitcoin-roots/shared.ts']), 'identical source retains all three repository paths');
|
|
1085
|
-
record('exclusions', await contains('multi', ['vendor/fixture.ts'], ['node_modules/fixture.ts', 'secrets/fixture.ts', '.hidden/fixture.ts', 'bitcoin-core/ignored.ts']), 'native ignore policy, hidden names, gitignore and vendor override');
|
|
1086
|
-
await writeFile(join(multi, 'bitcoin-core', 'unique.ts'), 'export const repository = "edited-marker";\n');
|
|
1087
|
-
await rm(join(multi, 'bitcoin-knots', 'unique.ts'));
|
|
1088
|
-
const edited = await index(multi, 'multi');
|
|
1089
|
-
requirePass('edit-delete', succeeded(edited) && await contains('multi', ['bitcoin-core/unique.ts'], ['bitcoin-knots/unique.ts']) && JSON.stringify(await hits('multi')).includes('edited-marker'), 'existing content updates and deleted paths disappear');
|
|
1090
|
-
const before = (await hits('multi')).map(hit => hit._id).sort();
|
|
1091
|
-
await stop(server); server = launch(binary, serverArgs, 0);
|
|
1092
|
-
requirePass('persistence', await ready() && succeeded(await index(multi, 'multi')) && JSON.stringify((await hits('multi')).map(hit => hit._id).sort()) === JSON.stringify(before), 'backend restart and unchanged reindex retain document IDs');
|
|
1093
|
-
const single = join(directory, 'single'); await git(single);
|
|
1094
|
-
await writeFile(join(single, 'one.ts'), 'export const one = 1;\n');
|
|
1095
|
-
requirePass('single-initial', succeeded(await index(single, 'single')), 'single-repository control');
|
|
1096
|
-
await writeFile(join(single, 'two.ts'), 'export const two = 2;\n');
|
|
1097
|
-
await mkdir(join(single, 'nested')); await writeFile(join(single, 'nested', 'three.ts'), 'export const three = 3;\n');
|
|
1098
|
-
requirePass('single-additions', succeeded(await index(single, 'single')) && await contains('single', ['two.ts', 'nested/three.ts']), 'adjacent files and new subdirectories work incrementally');
|
|
1099
|
-
const adjacent = join(multi, 'bitcoin-core', 'adjacent.ts');
|
|
1100
|
-
await writeFile(adjacent, 'export const adjacent = true;\n');
|
|
1101
|
-
let result = await index(multi, 'multi');
|
|
1102
|
-
record('existing-repository-addition', succeeded(result) && await contains('multi', ['bitcoin-core/adjacent.ts']), result.stderr.includes('refusing ambiguous assignment') ? 'native ambiguous assignment still reproduced' : `native exit ${result.code}; verify new path is searchable`, 1230);
|
|
1103
|
-
await rm(adjacent); requirePass('addition-recovery', succeeded(await index(multi, 'multi')), 'removing test addition restores reconciliation');
|
|
1104
|
-
result = await index(single, 'single', ['--dataset', 'nonexistent-map-only-selection']);
|
|
1105
|
-
record('dataset-option-validation', result.code === 2 && /dataset/i.test(result.stderr), `map-only --dataset during indexing exits ${result.code}; expected usage rejection`, 1231);
|
|
1106
|
-
const watchArgs = [...args(multi, 'multi'), '--watch', '--debounce', '100'];
|
|
1107
|
-
const watcher = launch(binary, watchArgs, 0);
|
|
1108
|
-
requirePass('watch-start', await until(() => watcher.ended || successfulPass(watcher.stderr)) && !watcher.ended && successfulPass(watcher.stderr), 'native watcher starts on committed index');
|
|
1109
|
-
watcher.stderr = ''; await writeFile(adjacent, 'export const watchedAdjacent = true;\n');
|
|
1110
|
-
await until(() => watcher.ended || successfulPass(watcher.stderr) || watcher.stderr.includes('FAILED'));
|
|
1111
|
-
record('watched-existing-repository-addition', successfulPass(watcher.stderr) && await contains('multi', ['bitcoin-core/adjacent.ts']), watcher.stderr.includes('refusing ambiguous assignment') ? 'watch mode still refuses ambiguous new file' : 'watch must publish an adjacent new source file', 1230);
|
|
1112
|
-
watcher.stderr = ''; await rm(adjacent);
|
|
1113
|
-
requirePass('watch-recovery', await until(() => successfulPass(watcher.stderr)), 'watcher reconciles after fixture cleanup');
|
|
1114
|
-
watcher.stderr = ''; const addedRepo = join(multi, 'new-repository'); await git(addedRepo);
|
|
1115
|
-
await writeFile(join(addedRepo, 'new.ts'), 'export const newRepository = true;\n');
|
|
1116
|
-
await until(() => watcher.ended || successfulPass(watcher.stderr) || watcher.stderr.includes('FAILED'));
|
|
1117
|
-
record('new-repository-discovery', successfulPass(watcher.stderr) && await contains('multi', ['new-repository/new.ts']), 'separate probe: a wholly new repository becomes searchable', 1230);
|
|
1118
|
-
await stop(watcher);
|
|
1119
|
-
const ownerArgs = [...args(single, 'single'), '--watch', '--debounce', '100'];
|
|
1120
|
-
const first = launch(binary, ownerArgs, 0);
|
|
1121
|
-
requirePass('watch-owner-control', await until(() => first.ended || successfulPass(first.stderr)) && !first.ended, 'first native owner is watching');
|
|
1122
|
-
const second = launch(binary, ownerArgs, 0);
|
|
1123
|
-
await until(() => second.ended || successfulPass(second.stderr), 10000);
|
|
1124
|
-
record('exclusive-native-watcher', second.ended && Number.isInteger(second.code) && second.code > 0 &&
|
|
1125
|
-
!successfulPass(second.stderr) && /lock|already.*watch|watch.*already|owner|busy/i.test(second.stderr),
|
|
1126
|
-
second.ended ? `second watcher exits ${second.code}; expected an ownership refusal` : 'both native watchers remain alive for the same journal', 1232);
|
|
1127
|
-
await stop(second); await stop(first);
|
|
1128
|
-
const replacement = launch(binary, ownerArgs, 0);
|
|
1129
|
-
requirePass('watch-lock-release', await until(() => replacement.ended || successfulPass(replacement.stderr)) && !replacement.ended, 'watcher can restart after owners exit');
|
|
1130
|
-
await stop(replacement);
|
|
1131
|
-
const capRoot = join(directory, 'cap'); await git(capRoot);
|
|
1132
|
-
await writeFile(join(capRoot, 'small.ts'), 'export const small = true;\n');
|
|
1133
|
-
await writeFile(join(capRoot, 'large.txt'), 'source-like generated artifact\n'.repeat(450000));
|
|
1134
|
-
const capArgs = args(capRoot, 'cap');
|
|
1135
|
-
const help = await launch(binary, ['autoindex', '--help'], 5000).done;
|
|
1136
|
-
const options = help.stdout + help.stderr;
|
|
1137
|
-
const capIndex = capArgs.indexOf('--max-file-gb');
|
|
1138
|
-
// Upstream may fix #1233 with a new unit option rather than fractional GB.
|
|
1139
|
-
if (/--max-file-bytes\b/.test(options)) capArgs.splice(capIndex, 2, '--max-file-bytes', '10000000');
|
|
1140
|
-
else if (/--max-file-mb\b/.test(options)) capArgs.splice(capIndex, 2, '--max-file-mb', '10');
|
|
1141
|
-
else capArgs[capIndex + 1] = '0.01';
|
|
1142
|
-
result = await launch(binary, capArgs).done;
|
|
1143
|
-
record('sub-gb-file-cap', [0, 3].includes(result.code) && await contains('cap', ['small.ts'], ['large.txt']),
|
|
1144
|
-
`${capArgs[capIndex]} ${capArgs[capIndex + 1]}: native exit ${result.code}; expected small file included and oversized file excluded`, 1233);
|
|
1145
|
-
} catch (error) {
|
|
1146
|
-
rows.push({ name: 'harness', status: 'error', detail: interrupted ? 'interrupted or overall deadline exceeded' : String(error.message).replaceAll(directory, '<temporary>') });
|
|
1147
|
-
} finally {
|
|
1148
|
-
clearTimeout(deadline);
|
|
1149
|
-
for (const child of [...children]) {
|
|
1150
|
-
child.kill('SIGTERM');
|
|
1151
|
-
const timer = setTimeout(() => child.kill('SIGKILL'), 2000);
|
|
1152
|
-
await new Promise(resolve => { if (child.exitCode !== null || child.signalCode !== null) resolve(); else child.once('close', resolve); });
|
|
1153
|
-
clearTimeout(timer);
|
|
1154
|
-
}
|
|
1155
|
-
await rm(directory, { recursive: true, force: true });
|
|
1156
|
-
process.removeListener('SIGINT', onSignal); process.removeListener('SIGTERM', onSignal);
|
|
1157
|
-
}
|
|
1158
|
-
const errors = rows.filter(row => row.status === 'error').length;
|
|
1159
|
-
const failed = rows.filter(row => row.status === 'fail').length;
|
|
1160
|
-
const report = { schemaVersion: 1, version, passed: rows.filter(row => row.status === 'pass').length, failed, errors, results: rows };
|
|
1161
|
-
if (json) console.log(JSON.stringify(report));
|
|
1162
|
-
else {
|
|
1163
|
-
for (const row of rows.filter(row => row.status === 'error')) console.log(`ERROR ${row.name}: ${row.detail}`);
|
|
1164
|
-
console.log(`${report.passed} passed, ${failed} failed, ${errors} errors. Temporary backend and data removed.`);
|
|
1165
|
-
console.log('Native issue probes only; a pass does not certify Mobile/MCP protocol compatibility or real-index migration.');
|
|
1166
|
-
}
|
|
1167
|
-
process.exitCode = interrupted ? 130 : errors ? 2 : failed ? 1 : 0;
|
|
1168
|
-
JS
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
validate_xerj_arguments() {
|
|
1172
|
-
local mode=$1 option value
|
|
1173
|
-
shift
|
|
1174
|
-
xerj_user_args=()
|
|
1175
|
-
while (($# > 0)); do
|
|
1176
|
-
option=$1
|
|
1177
|
-
shift
|
|
1178
|
-
if "$index_status"; then
|
|
1179
|
-
case $option in
|
|
1180
|
-
--cwd | --cwd=* | --prefix | --url | --api-key | --help | -h | --json | --md | --quiet | --disable-feedback) ;;
|
|
1181
|
-
*) die "unsupported managed xerj autoindex status option: $option" ;;
|
|
1182
|
-
esac
|
|
1183
|
-
fi
|
|
1184
|
-
if [[ $mode == autoindex && ( $option == --cwd || $option == --cwd=* ) ]]; then
|
|
1185
|
-
[[ -z $index_source ]] || die 'xerj autoindex accepts either --cwd or one positional source, not both'
|
|
1186
|
-
if [[ $option == --cwd ]]; then
|
|
1187
|
-
(($# > 0)) || die 'xerj --cwd requires a directory'
|
|
1188
|
-
value=$1
|
|
1189
|
-
shift
|
|
1190
|
-
else
|
|
1191
|
-
value=${option#--cwd=}
|
|
1192
|
-
fi
|
|
1193
|
-
[[ -n $value && $value != -* && -d $value ]] || die 'xerj --cwd requires an existing directory'
|
|
1194
|
-
index_source=$(CDPATH='' cd -- "$value" && pwd -P)
|
|
1195
|
-
index_cwd=true
|
|
1196
|
-
if ! "$index_status"; then xerj_user_args+=("$index_source"); fi
|
|
1197
|
-
continue
|
|
1198
|
-
fi
|
|
1199
|
-
xerj_user_args+=("$option")
|
|
1200
|
-
case $mode:$option in
|
|
1201
|
-
server:--bind | server:-b)
|
|
1202
|
-
(($# > 0)) || die "xerj option requires a value: $option"
|
|
1203
|
-
validate_xerj_bind "$1"
|
|
1204
|
-
xerj_user_args+=("$1")
|
|
1205
|
-
shift ;;
|
|
1206
|
-
autoindex:--url | search:--url | def:--url | gain:--url | mcp:--url)
|
|
1207
|
-
(($# > 0)) || die "xerj option requires a value: $option"
|
|
1208
|
-
validate_xerj_url "$1"
|
|
1209
|
-
xerj_user_args+=("$validated_xerj_url")
|
|
1210
|
-
shift ;;
|
|
1211
|
-
mcp:--auth)
|
|
1212
|
-
if (($# == 0)) || [[ -z $1 ]]; then die 'MCP --auth requires a nonempty value'; fi
|
|
1213
|
-
xerj_user_args+=("$1")
|
|
1214
|
-
shift ;;
|
|
1215
|
-
server:--data-dir | server:-d | index:--data-dir | index:-d)
|
|
1216
|
-
if (($# == 0)) || [[ $1 != "$xerj_data" ]]; then
|
|
1217
|
-
die 'xerj data directory is managed; omit the override'
|
|
1218
|
-
fi
|
|
1219
|
-
xerj_user_args+=("$1")
|
|
1220
|
-
shift ;;
|
|
1221
|
-
autoindex:--state-dir)
|
|
1222
|
-
if (($# == 0)) || [[ $1 != "$xerj_data/autoindex" ]]; then
|
|
1223
|
-
die 'xerj autoindex state directory is managed'
|
|
1224
|
-
fi
|
|
1225
|
-
xerj_user_args+=("$1")
|
|
1226
|
-
shift ;;
|
|
1227
|
-
server:--config | server:-c | index:--config | index:-c | *:--config=* | *:--data-dir=* | *:--state-dir=* | *:--events-out* | *:--status-file*)
|
|
1228
|
-
die "xerj path override is not supported: $option" ;;
|
|
1229
|
-
server:--help | server:-h | server:--version | server:-V | server:--insecure | server:-k | *:--disable-feedback | index:--help | index:-h | autoindex:--help | autoindex:-h | autoindex:--fresh | autoindex:--follow-symlinks | autoindex:--follow-symlinks-outside-root | autoindex:--no-ignore | autoindex:--no-default-ignores | autoindex:--no-semantic | autoindex:--no-graph | autoindex:--watch | autoindex:--yes | autoindex:-y | autoindex:--dry-run | autoindex:--json | autoindex:--md | autoindex:--quiet | autoindex:--once | autoindex:--no-fetch | autoindex:--append-only | autoindex:--allow-cost | search:--help | search:-h | search:--json | def:--help | def:-h | def:--json | gain:--help | gain:-h | gain:--json | mcp:--help | mcp:-h | mcp:--version | mcp:-V)
|
|
1230
|
-
;;
|
|
1231
|
-
server:--port | server:--embed-mode | server:--compat-distribution | server:--compat-version | server:--decide-mode | index:--index | index:-i | index:--file | index:-f | index:--batch | index:-b | index:--workers | index:-w | index:--limit | index:-l | autoindex:--api-key | autoindex:--workers | autoindex:--pdf-workers | autoindex:--pdf-timeout-secs | autoindex:--bulk-mb | autoindex:--bulk-timeout-secs | autoindex:--snapshot-max-gb | autoindex:--in-flight | autoindex:--prefix | autoindex:--endpoint-url | autoindex:--label | autoindex:--stub | autoindex:--max-file-gb | autoindex:--sample | autoindex:--brain | autoindex:--debounce | autoindex:--max-minutes | autoindex:--approve | autoindex:--progress | autoindex:--progress-interval | autoindex:--dataset | autoindex:--poll-interval | autoindex:--max-cycles | autoindex:--region | autoindex:--max-object-mb | autoindex:--max-monthly-ops | autoindex:--max-monthly-gets | autoindex:--page-size | search:--prefix | search:--api-key | search:-k | search:--full | def:--prefix | def:--api-key | def:-n | def:--kind | def:--lang | gain:--api-key)
|
|
1232
|
-
(($# > 0)) || die "xerj option requires a value: $option"
|
|
1233
|
-
value=$1
|
|
1234
|
-
[[ $value != -* ]] || die "xerj option requires a value, not a flag: $option"
|
|
1235
|
-
if [[ $mode == autoindex && $option == --prefix ]]; then index_prefix=$value; fi
|
|
1236
|
-
xerj_user_args+=("$value")
|
|
1237
|
-
shift ;;
|
|
1238
|
-
autoindex:* | search:* | def:*)
|
|
1239
|
-
[[ $option != -* ]] || die "unsupported managed xerj $mode option: $option"
|
|
1240
|
-
if [[ $mode == autoindex && $index_cwd == true ]]; then
|
|
1241
|
-
die 'xerj autoindex accepts either --cwd or one positional source, not both'
|
|
1242
|
-
fi
|
|
1243
|
-
if [[ $mode == autoindex && -z $index_source ]]; then index_source=$option; fi ;;
|
|
1244
|
-
*) die "unsupported managed xerj $mode option: $option" ;;
|
|
1245
|
-
esac
|
|
898
|
+
[[ ! -L $current ]] || die "managed path cannot traverse a symbolic link: $current"
|
|
1246
899
|
done
|
|
1247
900
|
}
|
|
1248
901
|
|
|
1249
|
-
command_xerj_readiness() {
|
|
1250
|
-
local operation=$1
|
|
1251
|
-
shift
|
|
1252
|
-
local service_workspace=''
|
|
1253
|
-
if (($# == 2)) && [[ $1 == --cwd ]]; then service_workspace=$2; shift 2; fi
|
|
1254
|
-
(($# == 0)) || die "usage: gestalt xerj $operation [--cwd ROOT]"
|
|
1255
|
-
require_command node
|
|
1256
|
-
# Inline to preserve the self-contained, single-file manager distribution.
|
|
1257
|
-
# Do not use command_xerj mcp: ordinary forwarding prepares writable state.
|
|
1258
|
-
exec node --input-type=module - "$gestalt_home" "$operation" "${BASH_SOURCE[0]}" "$codex_home" "$service_workspace" <<'JS'
|
|
1259
|
-
import { spawn } from 'node:child_process';
|
|
1260
|
-
import { lstatSync, readdirSync, constants as fsConstants } from 'node:fs';
|
|
1261
|
-
import { setImmediate as yieldToIO } from 'node:timers/promises';
|
|
1262
|
-
import { lstat, stat as followStat, readFile, realpath, readdir, mkdir, writeFile, rename, rm, chmod, open } from 'node:fs/promises';
|
|
1263
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
1264
|
-
import net from 'node:net';
|
|
1265
|
-
import { dirname, join, basename, relative } from 'node:path';
|
|
1266
|
-
import http from 'node:http';
|
|
1267
|
-
import { createRequire } from 'node:module';
|
|
1268
|
-
|
|
1269
|
-
const [selectedRoot, operation, managerPath, selectedCodexHome, serviceWorkspace] = process.argv.slice(2);
|
|
1270
|
-
const expires = Date.now() + (Number.isSafeInteger(Number(process.env.XERJ_READY_TIMEOUT_MS ?? '5000')) ? Number(process.env.XERJ_READY_TIMEOUT_MS ?? '5000') : 5000);
|
|
1271
|
-
const configured = process.env.XERJ_READY_TIMEOUT_MS ?? '5000';
|
|
1272
|
-
const timeout = /^\d+$/.test(configured) ? Number(configured) : NaN;
|
|
1273
|
-
const children = new Set();
|
|
1274
|
-
const requests = new Set();
|
|
1275
|
-
const controller = new AbortController();
|
|
1276
|
-
let timer;
|
|
1277
|
-
const fail = reason => { throw new Error(reason); };
|
|
1278
|
-
const cancel = () => controller.abort(new Error('cancelled'));
|
|
1279
|
-
process.on('SIGTERM', cancel);
|
|
1280
|
-
process.on('SIGINT', cancel);
|
|
1281
|
-
const bounded = operation => Promise.race([operation, new Promise((_, reject) => {
|
|
1282
|
-
if (controller.signal.aborted) reject(controller.signal.reason);
|
|
1283
|
-
else controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });
|
|
1284
|
-
})]);
|
|
1285
|
-
async function stat(path) {
|
|
1286
|
-
controller.signal.throwIfAborted();
|
|
1287
|
-
try {
|
|
1288
|
-
const info = await lstat(path);
|
|
1289
|
-
controller.signal.throwIfAborted();
|
|
1290
|
-
return info;
|
|
1291
|
-
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
1292
|
-
}
|
|
1293
|
-
async function safeTree(path, dataRoot) {
|
|
1294
|
-
// Snapshot histories can contain tens of thousands of files. Keep every
|
|
1295
|
-
// lstat/link check without a promise round trip per file. Yield between
|
|
1296
|
-
// bounded batches so cancellation and the shared deadline remain effective.
|
|
1297
|
-
const pending = [path];
|
|
1298
|
-
while (pending.length) {
|
|
1299
|
-
controller.signal.throwIfAborted();
|
|
1300
|
-
for (let count = 0; count < 256 && pending.length; count++) {
|
|
1301
|
-
const path = pending.pop();
|
|
1302
|
-
let info;
|
|
1303
|
-
try { info = lstatSync(path); }
|
|
1304
|
-
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
1305
|
-
// Snapshot blobs and prepared documents are immutable and natively linked.
|
|
1306
|
-
// Never exempt symlinks, or hard links in mutable state and installation files.
|
|
1307
|
-
const snapshotContent = dataRoot && /^autoindex\/[^/]+\/sync-snapshots\/[^/]+\/(blobs|prepared)\/[^/]+$/.test(relative(dataRoot, path));
|
|
1308
|
-
if (info.isSymbolicLink() || (info.isFile() && info.nlink > 1 && !snapshotContent)) fail('unsafe-path');
|
|
1309
|
-
if (info.isDirectory()) {
|
|
1310
|
-
try { for (const name of readdirSync(path)) pending.push(join(path, name)); }
|
|
1311
|
-
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
await yieldToIO();
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
async function canonicalRoot(selected) {
|
|
1318
|
-
if (!selected.startsWith('/') || /[\x00-\x1f\x7f]/.test(selected) ||
|
|
1319
|
-
selected.endsWith('/') || selected.includes('//') || selected.split('/').some(p => p === '.' || p === '..')) fail('unsafe-path');
|
|
1320
|
-
let ancestor = selected;
|
|
1321
|
-
const suffix = [];
|
|
1322
|
-
while (true) {
|
|
1323
|
-
const info = await stat(ancestor);
|
|
1324
|
-
if (info?.isDirectory() || (info?.isSymbolicLink() && (await followStat(ancestor)).isDirectory())) break;
|
|
1325
|
-
if (info) fail('unsafe-path');
|
|
1326
|
-
suffix.unshift(basename(ancestor)); ancestor = dirname(ancestor);
|
|
1327
|
-
}
|
|
1328
|
-
return join(await realpath(ancestor), ...suffix);
|
|
1329
|
-
}
|
|
1330
|
-
async function paths() {
|
|
1331
|
-
const root = await canonicalRoot(selectedRoot);
|
|
1332
|
-
const codexHome = await canonicalRoot(selectedCodexHome);
|
|
1333
|
-
const binary = join(root, 'xerj', 'xerj'), dataRoot = join(codexHome, 'xerj-data');
|
|
1334
|
-
for (const path of [join(root, 'xerj'), dataRoot]) {
|
|
1335
|
-
if ((await stat(path))?.isSymbolicLink()) fail('unsafe-path');
|
|
1336
|
-
}
|
|
1337
|
-
await safeTree(join(root, 'xerj')); await safeTree(dataRoot, dataRoot);
|
|
1338
|
-
if (process.env.XERJ_INSTALL_DIR && process.env.XERJ_INSTALL_DIR !== join(root, 'xerj')) fail('unsupported-installation');
|
|
1339
|
-
if ((process.env.XERJ_REPO && process.env.XERJ_REPO !== 'xerj-org/xerj') ||
|
|
1340
|
-
(process.env.XERJ_INSECURE_SKIP_CHECKSUM && process.env.XERJ_INSECURE_SKIP_CHECKSUM !== '0')) fail('unsupported-installation');
|
|
1341
|
-
return { root, binary, dataRoot };
|
|
1342
|
-
}
|
|
1343
|
-
function launch(binary, args, env) {
|
|
1344
|
-
controller.signal.throwIfAborted();
|
|
1345
|
-
const child = spawn(binary, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
1346
|
-
children.add(child);
|
|
1347
|
-
child.once('close', () => children.delete(child));
|
|
1348
|
-
// Never echo native diagnostics: they may contain authorization headers.
|
|
1349
|
-
child.stderr.resume();
|
|
1350
|
-
return child;
|
|
1351
|
-
}
|
|
1352
|
-
async function binaryVersion(binary, env) {
|
|
1353
|
-
const child = launch(binary, ['--version'], env);
|
|
1354
|
-
let output = '';
|
|
1355
|
-
child.stdout.on('data', chunk => {
|
|
1356
|
-
output += chunk;
|
|
1357
|
-
if (output.length > 1024) controller.abort(new Error('unsupported-version'));
|
|
1358
|
-
});
|
|
1359
|
-
const code = await new Promise((resolve, reject) => {
|
|
1360
|
-
child.once('error', () => reject(new Error('unsupported-binary')));
|
|
1361
|
-
child.once('close', resolve);
|
|
1362
|
-
});
|
|
1363
|
-
const match = /^xerj v?([0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?)$/.exec(output.trim());
|
|
1364
|
-
if (code !== 0 || !match) fail('unsupported-version');
|
|
1365
|
-
return match[1];
|
|
1366
|
-
}
|
|
1367
|
-
function get(url, auth) {
|
|
1368
|
-
controller.signal.throwIfAborted();
|
|
1369
|
-
return new Promise((resolve, reject) => {
|
|
1370
|
-
const request = http.get(url, { headers: { Authorization: auth }, signal: controller.signal }, response => {
|
|
1371
|
-
let body = '';
|
|
1372
|
-
response.on('data', chunk => {
|
|
1373
|
-
body += chunk;
|
|
1374
|
-
if (body.length > 262144) request.destroy(new Error('invalid-backend'));
|
|
1375
|
-
});
|
|
1376
|
-
response.on('error', () => reject(new Error('backend-unavailable')));
|
|
1377
|
-
response.on('end', () => {
|
|
1378
|
-
if (response.statusCode === 401 || response.statusCode === 403) return reject(new Error('authentication-failed'));
|
|
1379
|
-
if (response.statusCode !== 200) return reject(new Error('invalid-backend'));
|
|
1380
|
-
try { resolve(JSON.parse(body)); } catch { reject(new Error('invalid-backend')); }
|
|
1381
|
-
});
|
|
1382
|
-
});
|
|
1383
|
-
requests.add(request);
|
|
1384
|
-
request.on('close', () => requests.delete(request));
|
|
1385
|
-
request.on('error', () => reject(new Error('backend-unavailable')));
|
|
1386
|
-
});
|
|
1387
|
-
}
|
|
1388
|
-
async function mcp(binary, endpoint, env, version) {
|
|
1389
|
-
const child = launch(binary, ['mcp', '--url', endpoint], env);
|
|
1390
|
-
let buffer = '', total = 0;
|
|
1391
|
-
const pending = new Map();
|
|
1392
|
-
const refuse = () => {
|
|
1393
|
-
for (const { reject } of pending.values()) reject(new Error('invalid-mcp'));
|
|
1394
|
-
pending.clear();
|
|
1395
|
-
};
|
|
1396
|
-
child.on('error', refuse); child.on('close', refuse);
|
|
1397
|
-
child.stdin.on('error', refuse);
|
|
1398
|
-
child.stdout.on('data', chunk => {
|
|
1399
|
-
total += chunk.length; buffer += chunk;
|
|
1400
|
-
if (total > 262144) { refuse(); controller.abort(new Error('invalid-mcp')); return; }
|
|
1401
|
-
let end;
|
|
1402
|
-
while ((end = buffer.indexOf('\n')) >= 0) {
|
|
1403
|
-
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
1404
|
-
try {
|
|
1405
|
-
const message = JSON.parse(line);
|
|
1406
|
-
if (message.jsonrpc !== '2.0' || !pending.has(message.id) || message.error || !message.result || Array.isArray(message.result)) {
|
|
1407
|
-
refuse(); controller.abort(new Error('invalid-mcp')); return;
|
|
1408
|
-
}
|
|
1409
|
-
pending.get(message.id).resolve(message.result); pending.delete(message.id);
|
|
1410
|
-
} catch { refuse(); controller.abort(new Error('invalid-mcp')); return; }
|
|
1411
|
-
}
|
|
1412
|
-
});
|
|
1413
|
-
const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
1414
|
-
const rpc = (id, method, params) => new Promise((resolve, reject) => {
|
|
1415
|
-
pending.set(id, { resolve, reject }); send({ jsonrpc: '2.0', id, method, params });
|
|
1416
|
-
});
|
|
1417
|
-
const initialized = await rpc(1, 'initialize', {
|
|
1418
|
-
protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'gestalt-readiness', version: '1' }
|
|
1419
|
-
});
|
|
1420
|
-
if (initialized.protocolVersion !== '2025-03-26' || !initialized.capabilities?.tools ||
|
|
1421
|
-
initialized.serverInfo?.name !== 'xerj-mcp' || initialized.serverInfo?.version !== version) fail('incompatible-mcp');
|
|
1422
|
-
send({ jsonrpc: '2.0', method: 'notifications/initialized' });
|
|
1423
|
-
const listed = await rpc(2, 'tools/list', {});
|
|
1424
|
-
if (!Array.isArray(listed.tools) || listed.nextCursor || !['xerj_search', 'xerj_map', 'xerj_code_search'].every(name =>
|
|
1425
|
-
listed.tools.some(tool => tool.name === name && tool.inputSchema?.type === 'object'))) fail('incompatible-mcp');
|
|
1426
|
-
child.stdin.end();
|
|
1427
|
-
await new Promise((resolve, reject) => {
|
|
1428
|
-
child.once('close', code => code === 0 ? resolve() : reject(new Error('invalid-mcp')));
|
|
1429
|
-
child.once('error', () => reject(new Error('invalid-mcp')));
|
|
1430
|
-
});
|
|
1431
|
-
}
|
|
1432
|
-
async function probe() {
|
|
1433
|
-
const { root, binary, dataRoot } = await paths();
|
|
1434
|
-
const info = await stat(binary);
|
|
1435
|
-
if (!info) return { schemaVersion: 1, status: 'absent' };
|
|
1436
|
-
if (!info.isFile() || !(info.mode & 0o111)) fail('unsupported-binary');
|
|
1437
|
-
const endpoint = endpointOf();
|
|
1438
|
-
let key = process.env.XERJ_API_KEY ?? '';
|
|
1439
|
-
if (!key && await stat(join(dataRoot, 'admin.key'))) key = (await readFile(join(dataRoot, 'admin.key'), 'utf8')).trim();
|
|
1440
|
-
const auth = process.env.XERJ_AUTH || (key ? `ApiKey ${key}` : '');
|
|
1441
|
-
if (!auth || /[\r\n\x00]/.test(auth)) fail('credentials-unavailable');
|
|
1442
|
-
const env = nativeEnvironment(root, dataRoot, endpoint, auth);
|
|
1443
|
-
const version = await binaryVersion(binary, env);
|
|
1444
|
-
await mcp(binary, endpoint, env, version);
|
|
1445
|
-
// rc.87 es_compat::cluster_health + cat_indices_inner use engine reads.
|
|
1446
|
-
// Unlike _search (including MCP xerj_search), these successful GETs do not
|
|
1447
|
-
// append audit state. Missing autoindex-catalog is normal on an empty node.
|
|
1448
|
-
const health = await get(`${endpoint}/_cluster/health`, auth);
|
|
1449
|
-
if (health.cluster_name !== 'xerj' || !['green', 'yellow'].includes(health.status) ||
|
|
1450
|
-
health.timed_out !== false || !(health.number_of_nodes >= 1)) fail('invalid-backend');
|
|
1451
|
-
const indices = await get(`${endpoint}/_cat/indices?format=json&h=index`, auth);
|
|
1452
|
-
if (!Array.isArray(indices) || !indices.every(row => typeof row.index === 'string')) fail('invalid-backend');
|
|
1453
|
-
return { schemaVersion: 1, status: 'ready', version, endpoint, binary, dataRoot,
|
|
1454
|
-
auth: { environment: 'XERJ_AUTH', keyFile: join(dataRoot, 'admin.key') }, protocolVersion: '2025-03-26' };
|
|
1455
|
-
}
|
|
1456
|
-
function endpointOf(raw = process.env.XERJ_URL ?? 'http://127.0.0.1:9200') {
|
|
1457
|
-
if (!/^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d{1,5})?\/?$/.test(raw)) fail('unsafe-endpoint');
|
|
1458
|
-
let endpoint;
|
|
1459
|
-
try {
|
|
1460
|
-
const url = new URL(raw.replace('http://localhost', 'http://127.0.0.1'));
|
|
1461
|
-
if (!Number(url.port || 80) || Number(url.port || 80) > 65535) fail('unsafe-endpoint');
|
|
1462
|
-
endpoint = url.origin;
|
|
1463
|
-
} catch { fail('unsafe-endpoint'); }
|
|
1464
|
-
return endpoint;
|
|
1465
|
-
}
|
|
1466
|
-
function nativeEnvironment(root, dataRoot, endpoint, auth) {
|
|
1467
|
-
return {
|
|
1468
|
-
HOME: process.env.HOME, PATH: process.env.PATH, GESTALT_HOME: root, CODEX_HOME: dirname(dataRoot),
|
|
1469
|
-
XERJ_INSTALL_DIR: join(root, 'xerj'), XERJ_URL: endpoint, XERJ_AUTH: auth,
|
|
1470
|
-
XERJ_CODE_HOME: join(dataRoot, 'code'), XERJ_DISABLE_FEEDBACK: 'true', XERJ_LOG: 'off',
|
|
1471
|
-
XDG_CACHE_HOME: join(dataRoot, 'cache'), XDG_CONFIG_HOME: join(dataRoot, 'config'),
|
|
1472
|
-
XDG_DATA_HOME: join(dataRoot, 'share'), HF_HOME: join(dataRoot, 'cache', 'huggingface'), TMPDIR: join(dataRoot, 'tmp')
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
|
|
1476
|
-
function lifecyclePaths(dataRoot, endpoint) {
|
|
1477
|
-
const directory = join(dataRoot, '.lifecycle');
|
|
1478
|
-
const name = createHash('sha256').update(endpoint).digest('hex').slice(0, 16);
|
|
1479
|
-
return { directory, lock: join(directory, `${name}.lock`), record: join(directory, `${name}.json`),
|
|
1480
|
-
socket: join(directory, `${name}.sock`), log: join(directory, `${name}.log`) };
|
|
1481
|
-
}
|
|
1482
|
-
async function identity(pid) {
|
|
1483
|
-
if (!Number.isSafeInteger(pid) || pid < 1) return null;
|
|
1484
|
-
if (process.platform === 'linux') {
|
|
1485
|
-
try {
|
|
1486
|
-
const [record, boot] = await Promise.all([readFile(`/proc/${pid}/stat`, 'utf8'), readFile('/proc/sys/kernel/random/boot_id', 'utf8')]);
|
|
1487
|
-
return `${boot.trim()}:${record.slice(record.lastIndexOf(')') + 2).split(' ')[19]}`;
|
|
1488
|
-
} catch (error) { if (error.code === 'ENOENT' || error.code === 'ESRCH') return null; throw error; }
|
|
1489
|
-
}
|
|
1490
|
-
// macOS: birth time plus full command, never PID existence alone.
|
|
1491
|
-
const child = launch('ps', ['-p', String(pid), '-o', 'lstart=', '-o', 'command='], { PATH: process.env.PATH });
|
|
1492
|
-
let text = '';
|
|
1493
|
-
child.stdout.on('data', chunk => { text += chunk; if (text.length > 8192) child.kill('SIGKILL'); });
|
|
1494
|
-
const code = await new Promise((resolve, reject) => { child.once('close', resolve); child.once('error', reject); });
|
|
1495
|
-
return code === 0 && text.trim() ? text.trim() : null;
|
|
1496
|
-
}
|
|
1497
|
-
async function lifecycleSocketAddress(layout) {
|
|
1498
|
-
if (process.platform !== 'linux' || Buffer.byteLength(layout.socket) < 100)
|
|
1499
|
-
return {address: layout.socket, shortened: false, close: async () => {}};
|
|
1500
|
-
if (layout.socket !== join(layout.directory, basename(layout.socket)) ||
|
|
1501
|
-
!/^[a-f0-9]{16}\.sock$/.test(basename(layout.socket))) fail('unsafe-path');
|
|
1502
|
-
const handle = await open(layout.directory, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW);
|
|
1503
|
-
try {
|
|
1504
|
-
const held = await handle.stat(), current = await lstat(layout.directory);
|
|
1505
|
-
if (!held.isDirectory() || (held.mode & 0o777) !== 0o700 ||
|
|
1506
|
-
process.getuid && held.uid !== process.getuid() || current.isSymbolicLink() ||
|
|
1507
|
-
current.dev !== held.dev || current.ino !== held.ino ||
|
|
1508
|
-
await realpath(layout.directory) !== layout.directory) fail('unsafe-path');
|
|
1509
|
-
const descriptor = '/proc/' + process.pid + '/fd/' + handle.fd;
|
|
1510
|
-
const target = await followStat(descriptor);
|
|
1511
|
-
if (target.dev !== held.dev || target.ino !== held.ino) fail('unsafe-path');
|
|
1512
|
-
let closing;
|
|
1513
|
-
return {address: descriptor + '/' + basename(layout.socket), shortened: true, close: () => closing ??= handle.close()};
|
|
1514
|
-
} catch (error) {await handle.close(); throw error;}
|
|
1515
|
-
}
|
|
1516
|
-
async function readJSON(path) {
|
|
1517
|
-
try { return JSON.parse(await readFile(path, 'utf8')); }
|
|
1518
|
-
catch (error) { if (error.code === 'ENOENT') return null; fail('invalid-lifecycle-record'); }
|
|
1519
|
-
}
|
|
1520
|
-
async function atomicJSON(path, value) {
|
|
1521
|
-
const temporary = `${path}.${randomBytes(8).toString('hex')}.tmp`;
|
|
1522
|
-
try {
|
|
1523
|
-
await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
|
|
1524
|
-
await rename(temporary, path);
|
|
1525
|
-
} finally { await rm(temporary, { force: true }); }
|
|
1526
|
-
}
|
|
1527
|
-
async function acquireLock(layout, root, endpoint) {
|
|
1528
|
-
const token = randomBytes(24).toString('hex');
|
|
1529
|
-
const owner = { root, endpoint, pid: process.pid, identity: await identity(process.pid), token };
|
|
1530
|
-
if (!owner.identity) fail('lifecycle-busy');
|
|
1531
|
-
while (true) {
|
|
1532
|
-
controller.signal.throwIfAborted();
|
|
1533
|
-
try {
|
|
1534
|
-
await mkdir(layout.lock, { mode: 0o700 });
|
|
1535
|
-
await atomicJSON(join(layout.lock, 'owner.json'), owner);
|
|
1536
|
-
const release = async () => {
|
|
1537
|
-
const current = await readJSON(join(layout.lock, 'owner.json'));
|
|
1538
|
-
if (current?.token === token) await rm(layout.lock, { recursive: true });
|
|
1539
|
-
};
|
|
1540
|
-
release.token = token;
|
|
1541
|
-
return release;
|
|
1542
|
-
} catch (error) {
|
|
1543
|
-
if (error.code !== 'EEXIST') throw error;
|
|
1544
|
-
}
|
|
1545
|
-
const previous = await readJSON(join(layout.lock, 'owner.json'));
|
|
1546
|
-
// A new lock may not have its record yet. Unknown/malformed ownership is
|
|
1547
|
-
// never grounds to reclaim it; only a demonstrably dead/reused owner is.
|
|
1548
|
-
if (previous && previous.root === root && previous.endpoint === endpoint &&
|
|
1549
|
-
Number.isSafeInteger(previous.pid) && previous.pid > 0 &&
|
|
1550
|
-
typeof previous.identity === 'string' && /^[a-f0-9]{48}$/.test(previous.token) &&
|
|
1551
|
-
await identity(previous.pid) !== previous.identity) {
|
|
1552
|
-
const current = await readJSON(join(layout.lock, 'owner.json'));
|
|
1553
|
-
if (current?.token === previous.token) {
|
|
1554
|
-
// Serialize stale recovery independently so two recoverers cannot
|
|
1555
|
-
// remove a freshly acquired lock between comparison and removal.
|
|
1556
|
-
const recovery = `${layout.lock}.recovery`;
|
|
1557
|
-
try {
|
|
1558
|
-
await mkdir(recovery, { mode: 0o700 });
|
|
1559
|
-
try {
|
|
1560
|
-
const checked = await readJSON(join(layout.lock, 'owner.json'));
|
|
1561
|
-
if (checked?.token === previous.token && await identity(checked.pid) !== checked.identity)
|
|
1562
|
-
await rm(layout.lock, { recursive: true });
|
|
1563
|
-
} finally { await rm(recovery, { recursive: true }); }
|
|
1564
|
-
} catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
1565
|
-
}
|
|
1566
|
-
}
|
|
1567
|
-
await delay(20);
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
async function control(layout, token, method, allowAborted = false) {
|
|
1571
|
-
if (!allowAborted) controller.signal.throwIfAborted();
|
|
1572
|
-
// A stale record without a control socket cannot prove managed ownership.
|
|
1573
|
-
// Preserve that absent-channel result before opening a directory descriptor.
|
|
1574
|
-
let endpoint;
|
|
1575
|
-
try {endpoint = await lstat(layout.socket);}
|
|
1576
|
-
catch (error) {if (error.code === 'ENOENT') return null; throw error;}
|
|
1577
|
-
if (!endpoint.isSocket()) return null;
|
|
1578
|
-
const address = await lifecycleSocketAddress(layout);
|
|
1579
|
-
let socket, closed;
|
|
1580
|
-
try {
|
|
1581
|
-
if (!allowAborted) controller.signal.throwIfAborted();
|
|
1582
|
-
return await new Promise(resolve => {
|
|
1583
|
-
let text = '', done = false;
|
|
1584
|
-
socket = net.createConnection(address.address);
|
|
1585
|
-
closed = new Promise(resolve => socket.once('close', resolve));
|
|
1586
|
-
const complete = result => { if (!done) { done = true; clearTimeout(deadline); socket.destroy(); resolve(result); } };
|
|
1587
|
-
// Explicit stop includes native shutdown and filesystem cleanup. Its
|
|
1588
|
-
// acknowledgment can take longer than an info roundtrip, while failed
|
|
1589
|
-
// launch cleanup still stays within the reserved overall deadline.
|
|
1590
|
-
const budget = method === 'stop' && !allowAborted ? Math.min(1000, Math.max(1, expires - Date.now() - 100)) : 100;
|
|
1591
|
-
const deadline = setTimeout(() => complete(null), budget);
|
|
1592
|
-
socket.on('error', () => complete(null));
|
|
1593
|
-
socket.on('end', () => complete(null));
|
|
1594
|
-
socket.on('connect', () => socket.write(`${JSON.stringify({ token, method })}\n`));
|
|
1595
|
-
socket.on('data', chunk => {
|
|
1596
|
-
text += chunk;
|
|
1597
|
-
if (text.length > 16384) return complete(null);
|
|
1598
|
-
if (text.includes('\n')) {
|
|
1599
|
-
try { complete(JSON.parse(text.trim())); } catch { complete(null); }
|
|
1600
|
-
}
|
|
1601
|
-
});
|
|
1602
|
-
});
|
|
1603
|
-
} finally {
|
|
1604
|
-
socket?.destroy();
|
|
1605
|
-
if (address.shortened) await closed;
|
|
1606
|
-
await address.close();
|
|
1607
|
-
}
|
|
1608
|
-
}
|
|
1609
|
-
async function ownerAt(layout, root, endpoint) {
|
|
1610
|
-
const record = await readJSON(layout.record);
|
|
1611
|
-
if (!record) return null;
|
|
1612
|
-
if (record.root !== root || record.endpoint !== endpoint || !/^[a-f0-9]{48}$/.test(record.token)) fail('invalid-lifecycle-record');
|
|
1613
|
-
const result = await control(layout, record.token, 'info');
|
|
1614
|
-
return result?.root === root && result.endpoint === endpoint && result.serverAlive ? record : null;
|
|
1615
|
-
}
|
|
1616
|
-
async function listenerPresent(endpoint) {
|
|
1617
|
-
const url = new URL(endpoint);
|
|
1618
|
-
return new Promise((resolve, reject) => {
|
|
1619
|
-
const socket = net.createConnection({ host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 80) });
|
|
1620
|
-
const abort = () => { socket.destroy(); reject(controller.signal.reason); };
|
|
1621
|
-
controller.signal.addEventListener('abort', abort, { once: true });
|
|
1622
|
-
const finish = value => { controller.signal.removeEventListener('abort', abort); socket.destroy(); resolve(value); };
|
|
1623
|
-
socket.on('connect', () => finish(true));
|
|
1624
|
-
socket.on('error', error => error.code === 'ECONNREFUSED' ? finish(false) : finish(true));
|
|
1625
|
-
});
|
|
1626
|
-
}
|
|
1627
|
-
async function runGuardian() {
|
|
1628
|
-
const { root, dataRoot } = await paths();
|
|
1629
|
-
const endpoint = endpointOf(), layout = lifecyclePaths(dataRoot, endpoint);
|
|
1630
|
-
const token = process.env.GESTALT_XERJ_OWNER_TOKEN ?? '';
|
|
1631
|
-
const deadline = Number(process.env.GESTALT_XERJ_OWNER_DEADLINE);
|
|
1632
|
-
if (!/^[a-f0-9]{48}$/.test(token) || !Number.isSafeInteger(deadline) || deadline <= Date.now() || deadline > Date.now() + 60000)
|
|
1633
|
-
fail('invalid-lifecycle-record');
|
|
1634
|
-
const startupOwner = await readJSON(join(layout.lock, 'owner.json'));
|
|
1635
|
-
if (!startupOwner || startupOwner.root !== root || startupOwner.endpoint !== endpoint ||
|
|
1636
|
-
!Number.isSafeInteger(startupOwner.pid) || typeof startupOwner.identity !== 'string' ||
|
|
1637
|
-
startupOwner.token !== process.env.GESTALT_XERJ_STARTUP_LOCK_TOKEN ||
|
|
1638
|
-
await identity(startupOwner.pid) !== startupOwner.identity) fail('invalid-lifecycle-record');
|
|
1639
|
-
const runtimeSource = (await readFile(managerPath, 'utf8')).match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
|
|
1640
|
-
if (!runtimeSource) fail('scratch-runtime-unavailable');
|
|
1641
|
-
const scratch = new Function('require', runtimeSource[1] + '\nreturn {scratchAllocate,scratchEnvironment,scratchRelease,scratchStopped};')(createRequire(import.meta.url));
|
|
1642
|
-
const serviceOwnership = serviceWorkspace ? scratch.scratchAllocate(serviceWorkspace, 'workspace-service', 'xerj-backend') : null;
|
|
1643
|
-
if (!serviceOwnership) process.stderr.write('gestalt: no selected workspace; shared XERJ temporary ownership unavailable\n');
|
|
1644
|
-
let serverChild, controlServer, controlAddress, retained = false, stopping;
|
|
1645
|
-
const clients = new Set();
|
|
1646
|
-
const event = async name => {
|
|
1647
|
-
// Only manager event codes, never native stdout/stderr or credentials.
|
|
1648
|
-
let previous = '';
|
|
1649
|
-
try { previous = await readFile(layout.log, 'utf8'); } catch {}
|
|
1650
|
-
await writeFile(layout.log, `${previous}${Date.now()} ${name}\n`.slice(-32768), { mode: 0o600 });
|
|
1651
|
-
await chmod(layout.log, 0o600);
|
|
1652
|
-
};
|
|
1653
|
-
const stop = (failed = false) => stopping ??= (async () => {
|
|
1654
|
-
clearTimeout(startupTimer);
|
|
1655
|
-
// Control clients wait at most one second for stop acknowledgement. Keep
|
|
1656
|
-
// TERM grace and confirmed KILL/absence inside that existing protocol bound.
|
|
1657
|
-
const stopped = !serverChild || await scratch.scratchStopped(serverChild, true, {graceMs: 100, maxMs: 700});
|
|
1658
|
-
if (stopped && serviceOwnership) scratch.scratchRelease(serviceOwnership);
|
|
1659
|
-
const record = await readJSON(layout.record);
|
|
1660
|
-
if (stopped && record?.token === token) await rm(layout.record, { force: true });
|
|
1661
|
-
const address = controlAddress;
|
|
1662
|
-
controlAddress = undefined;
|
|
1663
|
-
if (controlServer) {
|
|
1664
|
-
for (const client of clients) client.destroy();
|
|
1665
|
-
// The stop requester receives its acknowledgement after this function.
|
|
1666
|
-
// Keep the fd through that final connection without awaiting it here.
|
|
1667
|
-
controlServer.close(() => {
|
|
1668
|
-
if (address) void address.close().catch(() => {
|
|
1669
|
-
process.stderr.write('gestalt: XERJ control descriptor close unconfirmed\n'); process.exitCode = 1;
|
|
1670
|
-
});
|
|
1671
|
-
});
|
|
1672
|
-
await rm(layout.socket, { force: true });
|
|
1673
|
-
} else await address?.close();
|
|
1674
|
-
await event(stopped ? failed ? 'failed-launch-reaped' : 'backend-stopped' : 'backend-stop-unconfirmed');
|
|
1675
|
-
return stopped;
|
|
1676
|
-
})();
|
|
1677
|
-
const startupTimer = setTimeout(() => { if (!retained) void stop(true); }, Math.max(1, deadline - Date.now() - 100));
|
|
1678
|
-
process.removeListener('SIGTERM', cancel); process.removeListener('SIGINT', cancel);
|
|
1679
|
-
process.on('SIGTERM', () => void stop()); process.on('SIGINT', () => void stop());
|
|
1680
|
-
try {
|
|
1681
|
-
if (await stat(layout.socket)) {
|
|
1682
|
-
// Only remove a stale control socket once exclusive startup ownership
|
|
1683
|
-
// has been obtained by ensure-ready and no guardian can answer.
|
|
1684
|
-
const old = await readJSON(layout.record);
|
|
1685
|
-
if (old && await control(layout, old.token, 'info')) fail('lifecycle-busy');
|
|
1686
|
-
await rm(layout.socket, { force: true });
|
|
1687
|
-
}
|
|
1688
|
-
controlServer = net.createServer(client => {
|
|
1689
|
-
clients.add(client); client.on('close', () => clients.delete(client));
|
|
1690
|
-
let input = '';
|
|
1691
|
-
client.setTimeout(1000, () => client.destroy());
|
|
1692
|
-
client.on('error', () => client.destroy());
|
|
1693
|
-
client.on('data', chunk => {
|
|
1694
|
-
input += chunk;
|
|
1695
|
-
if (input.length > 1024) return client.destroy();
|
|
1696
|
-
if (!input.includes('\n')) return;
|
|
1697
|
-
let request;
|
|
1698
|
-
try { request = JSON.parse(input.trim()); } catch { client.destroy(); return; }
|
|
1699
|
-
if (!request || typeof request !== 'object' || request.token !== token) { client.destroy(); return; }
|
|
1700
|
-
const alive = serverChild && serverChild.exitCode === null && serverChild.signalCode === null;
|
|
1701
|
-
const answer = value => client.end(`${JSON.stringify(value)}\n`);
|
|
1702
|
-
if (request.method === 'info') answer({ root, endpoint, serverAlive: Boolean(alive) });
|
|
1703
|
-
else if (request.method === 'retain' && alive && Date.now() < deadline) {
|
|
1704
|
-
retained = true; clearTimeout(startupTimer); answer({ retained: true });
|
|
1705
|
-
} else if (request.method === 'stop') {
|
|
1706
|
-
// Acknowledge only after the child this guardian owns is reaped.
|
|
1707
|
-
clients.delete(client);
|
|
1708
|
-
void stop().then(stopped => answer({ stopped })).catch(() => client.destroy());
|
|
1709
|
-
} else client.destroy();
|
|
1710
|
-
});
|
|
1711
|
-
});
|
|
1712
|
-
controlAddress = await lifecycleSocketAddress(layout);
|
|
1713
|
-
if (stopping || Date.now() >= deadline - 100) {
|
|
1714
|
-
await controlAddress?.close(); controlAddress = undefined; fail('timeout');
|
|
1715
|
-
}
|
|
1716
|
-
await new Promise((resolve, reject) => { controlServer.once('error', reject); controlServer.listen(controlAddress.address, resolve); });
|
|
1717
|
-
await chmod(layout.socket, 0o600);
|
|
1718
|
-
if (Date.now() >= deadline - 100 || stopping) fail('timeout');
|
|
1719
|
-
const env = nativeEnvironment(root, dataRoot, endpoint, process.env.XERJ_AUTH || 'ApiKey managed-key-unavailable');
|
|
1720
|
-
if (serviceOwnership) Object.assign(env, scratch.scratchEnvironment({...env,
|
|
1721
|
-
GESTALT_SESSION_TMP_CONTEXT: JSON.stringify(serviceOwnership.context)}));
|
|
1722
|
-
env.XERJ_API_KEY = process.env.XERJ_API_KEY || '';
|
|
1723
|
-
// The forwarding wrapper derives this confined path itself and rejects
|
|
1724
|
-
// inherited path overrides, including the proxy-only code-cache setting.
|
|
1725
|
-
delete env.XERJ_CODE_HOME;
|
|
1726
|
-
const url = new URL(endpoint);
|
|
1727
|
-
const executable = await realpath(managerPath);
|
|
1728
|
-
if (stopping || Date.now() >= deadline - 100) fail('timeout');
|
|
1729
|
-
serverChild = spawn('bash', [executable, 'xerj', '--port', String(url.port || 80),
|
|
1730
|
-
'--bind', url.hostname === '[::1]' ? '::1' : '127.0.0.1', '--embed-mode', 'lexical'],
|
|
1731
|
-
{ env, detached: true, stdio: ['ignore', 'ignore', 'ignore'] });
|
|
1732
|
-
serverChild.on('error', () => void stop(true));
|
|
1733
|
-
serverChild.on('close', () => { if (!stopping) void stop(true); });
|
|
1734
|
-
await atomicJSON(layout.record, { root, endpoint, token });
|
|
1735
|
-
if (stopping) {
|
|
1736
|
-
if ((await readJSON(layout.record))?.token === token) await rm(layout.record, { force: true });
|
|
1737
|
-
fail('timeout');
|
|
1738
|
-
}
|
|
1739
|
-
await event('backend-started');
|
|
1740
|
-
// Listening control socket and child keep this owner alive across clients.
|
|
1741
|
-
} catch (error) { await stop(true); throw error; }
|
|
1742
|
-
}
|
|
1743
|
-
async function lifecycle(automatic = false) {
|
|
1744
|
-
if (operation === 'probe') return probe();
|
|
1745
|
-
const { root, binary, dataRoot } = await paths();
|
|
1746
|
-
const endpoint = endpointOf(), layout = lifecyclePaths(dataRoot, endpoint);
|
|
1747
|
-
if (operation === 'status') {
|
|
1748
|
-
const ready = await probe();
|
|
1749
|
-
return { ...ready, ownership: await ownerAt(layout, root, endpoint) ? 'managed' : ready.status === 'ready' ? 'adopted' : 'none' };
|
|
1750
|
-
}
|
|
1751
|
-
if (operation === 'stop') {
|
|
1752
|
-
if (!(await stat(layout.directory))) fail('not-managed');
|
|
1753
|
-
const release = await acquireLock(layout, root, endpoint);
|
|
1754
|
-
try {
|
|
1755
|
-
const owner = await ownerAt(layout, root, endpoint);
|
|
1756
|
-
if (!owner) fail('not-managed');
|
|
1757
|
-
const response = await control(layout, owner.token, 'stop');
|
|
1758
|
-
if (!response?.stopped) fail('stop-failed');
|
|
1759
|
-
return { schemaVersion: 1, status: 'stopped', endpoint, dataRoot };
|
|
1760
|
-
} finally { await release(); }
|
|
1761
|
-
}
|
|
1762
|
-
const info = await stat(binary);
|
|
1763
|
-
if (!info) return { schemaVersion: 1, status: 'absent' };
|
|
1764
|
-
if (!info.isFile() || !(info.mode & 0o111)) fail('unsupported-binary');
|
|
1765
|
-
await binaryVersion(binary, nativeEnvironment(root, dataRoot, endpoint, 'ApiKey managed-key-unavailable'));
|
|
1766
|
-
await mkdir(layout.directory, { recursive: true, mode: 0o700 });
|
|
1767
|
-
await chmod(layout.directory, 0o700);
|
|
1768
|
-
const release = await acquireLock(layout, root, endpoint);
|
|
1769
|
-
let launchToken;
|
|
1770
|
-
try {
|
|
1771
|
-
try {
|
|
1772
|
-
const ready = await probe();
|
|
1773
|
-
if (ready.status === 'ready') return { ...ready, ownership: await ownerAt(layout, root, endpoint) ? 'managed' : 'adopted' };
|
|
1774
|
-
} catch (error) {
|
|
1775
|
-
if (controller.signal.aborted) throw error;
|
|
1776
|
-
if (!['credentials-unavailable', 'backend-unavailable', 'authentication-failed', 'invalid-backend'].includes(error.message)) throw error;
|
|
1777
|
-
}
|
|
1778
|
-
if (await listenerPresent(endpoint)) fail('endpoint-in-use');
|
|
1779
|
-
const previous = await ownerAt(layout, root, endpoint);
|
|
1780
|
-
if (previous) fail('lifecycle-busy');
|
|
1781
|
-
launchToken = randomBytes(24).toString('hex');
|
|
1782
|
-
const env = nativeEnvironment(root, dataRoot, endpoint, process.env.XERJ_AUTH || 'ApiKey managed-key-unavailable');
|
|
1783
|
-
env.XERJ_API_KEY = process.env.XERJ_API_KEY || '';
|
|
1784
|
-
env.GESTALT_XERJ_OWNER_TOKEN = launchToken;
|
|
1785
|
-
env.GESTALT_XERJ_OWNER_DEADLINE = String(expires);
|
|
1786
|
-
env.GESTALT_XERJ_STARTUP_LOCK_TOKEN = release.token;
|
|
1787
|
-
const executable = await realpath(managerPath);
|
|
1788
|
-
controller.signal.throwIfAborted();
|
|
1789
|
-
const guardian = spawn('bash', [executable, 'xerj', '__backend', ...(serviceWorkspace ? ['--cwd', serviceWorkspace] : [])], { env, detached: true, stdio: 'ignore' });
|
|
1790
|
-
guardian.on('error', () => controller.abort(new Error('launch-failed')));
|
|
1791
|
-
guardian.unref();
|
|
1792
|
-
let observedOwner = false;
|
|
1793
|
-
while (true) {
|
|
1794
|
-
controller.signal.throwIfAborted();
|
|
1795
|
-
await delay(25);
|
|
1796
|
-
if (guardian.exitCode !== null || guardian.signalCode !== null)
|
|
1797
|
-
fail(await listenerPresent(endpoint) ? 'endpoint-in-use' : 'launch-failed');
|
|
1798
|
-
const owner = await ownerAt(layout, root, endpoint);
|
|
1799
|
-
if (!owner || owner.token !== launchToken) {
|
|
1800
|
-
if (observedOwner && !(await stat(layout.record)))
|
|
1801
|
-
fail(await listenerPresent(endpoint) ? 'endpoint-in-use' : 'launch-failed');
|
|
1802
|
-
continue;
|
|
1803
|
-
}
|
|
1804
|
-
observedOwner = true;
|
|
1805
|
-
try {
|
|
1806
|
-
const ready = await probe();
|
|
1807
|
-
if (ready.status === 'ready' && (await control(layout, launchToken, 'retain'))?.retained) {
|
|
1808
|
-
controller.signal.throwIfAborted();
|
|
1809
|
-
launchToken = null;
|
|
1810
|
-
return { ...ready, ownership: 'managed' };
|
|
1811
|
-
}
|
|
1812
|
-
} catch (error) {
|
|
1813
|
-
if (controller.signal.aborted) throw error;
|
|
1814
|
-
if (automatic && ['authentication-failed', 'invalid-backend'].includes(error.message)) fail('endpoint-in-use');
|
|
1815
|
-
if (!['credentials-unavailable', 'backend-unavailable'].includes(error.message)) throw error;
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
} finally {
|
|
1819
|
-
if (launchToken) await control(layout, launchToken, 'stop', true);
|
|
1820
|
-
await release();
|
|
1821
|
-
}
|
|
1822
|
-
}
|
|
1823
|
-
async function automaticLifecycle() {
|
|
1824
|
-
if (process.env.XERJ_URL !== undefined) return lifecycle();
|
|
1825
|
-
const { root, dataRoot } = await paths();
|
|
1826
|
-
const file = join(dataRoot, '.lifecycle', 'endpoint.json');
|
|
1827
|
-
const selectSaved = async () => {
|
|
1828
|
-
const saved = await readJSON(file);
|
|
1829
|
-
if (saved && (saved.schemaVersion !== 1 || typeof saved.endpoint !== 'string')) fail('invalid-lifecycle-record');
|
|
1830
|
-
process.env.XERJ_URL = endpointOf(saved?.endpoint ?? 'http://127.0.0.1:9200');
|
|
1831
|
-
};
|
|
1832
|
-
if (operation !== 'ensure-ready') {
|
|
1833
|
-
await selectSaved();
|
|
1834
|
-
return lifecycle();
|
|
1835
|
-
}
|
|
1836
|
-
// Serialize endpoint selection across all clients of this data directory.
|
|
1837
|
-
// Endpoint-specific locks alone cannot serialize the initial allocation.
|
|
1838
|
-
const layout = lifecyclePaths(dataRoot, 'automatic');
|
|
1839
|
-
await mkdir(layout.directory, { recursive: true, mode: 0o700 });
|
|
1840
|
-
await chmod(layout.directory, 0o700);
|
|
1841
|
-
const release = await acquireLock(layout, root, 'automatic');
|
|
1842
|
-
try {
|
|
1843
|
-
await selectSaved();
|
|
1844
|
-
while (true) {
|
|
1845
|
-
try {
|
|
1846
|
-
const ready = await lifecycle(true);
|
|
1847
|
-
if (ready.status === 'ready') await atomicJSON(file, { schemaVersion: 1, endpoint: ready.endpoint });
|
|
1848
|
-
return ready;
|
|
1849
|
-
} catch (error) {
|
|
1850
|
-
if (error.message !== 'endpoint-in-use') throw error;
|
|
1851
|
-
}
|
|
1852
|
-
// The OS chooses a currently free loopback port. If another user wins
|
|
1853
|
-
// the bind race, the next lifecycle check retries within our deadline.
|
|
1854
|
-
controller.signal.throwIfAborted();
|
|
1855
|
-
const listener = net.createServer();
|
|
1856
|
-
await new Promise((resolve, reject) => {
|
|
1857
|
-
listener.once('error', reject);
|
|
1858
|
-
listener.listen(0, '127.0.0.1', resolve);
|
|
1859
|
-
});
|
|
1860
|
-
const port = listener.address().port;
|
|
1861
|
-
await new Promise(resolve => listener.close(resolve));
|
|
1862
|
-
process.env.XERJ_URL = `http://127.0.0.1:${port}`;
|
|
1863
|
-
}
|
|
1864
|
-
} finally { await release(); }
|
|
1865
|
-
}
|
|
1866
|
-
if (operation === '__backend') {
|
|
1867
|
-
try { await runGuardian(); } catch { process.exitCode = 1; }
|
|
1868
|
-
} else {
|
|
1869
|
-
let result;
|
|
1870
|
-
try {
|
|
1871
|
-
if (!Number.isSafeInteger(timeout) || timeout < 100 || timeout > 60000) fail('invalid-deadline');
|
|
1872
|
-
// Reserve cleanup time inside the overall budget, never after it.
|
|
1873
|
-
timer = setTimeout(() => controller.abort(new Error('timeout')), Math.max(1, timeout - 100));
|
|
1874
|
-
result = await bounded(automaticLifecycle());
|
|
1875
|
-
} catch (error) {
|
|
1876
|
-
const reasons = new Set(['cancelled', 'timeout', 'unsafe-path', 'unsupported-installation', 'unsupported-version',
|
|
1877
|
-
'unsupported-binary', 'unsafe-endpoint', 'credentials-unavailable', 'authentication-failed',
|
|
1878
|
-
'backend-unavailable', 'invalid-backend', 'invalid-mcp', 'incompatible-mcp', 'invalid-deadline',
|
|
1879
|
-
'invalid-lifecycle-record', 'lifecycle-busy', 'endpoint-in-use', 'not-managed', 'stop-failed', 'launch-failed']);
|
|
1880
|
-
const reason = controller.signal.aborted ? controller.signal.reason.message : error.message;
|
|
1881
|
-
result = { schemaVersion: 1, status: 'unavailable', reason: reasons.has(reason) ? reason : 'probe-failed' };
|
|
1882
|
-
} finally {
|
|
1883
|
-
clearTimeout(timer);
|
|
1884
|
-
controller.abort(new Error('cleanup'));
|
|
1885
|
-
for (const request of requests) request.destroy();
|
|
1886
|
-
const exits = [...children].map(child => new Promise(resolve => {
|
|
1887
|
-
child.once('close', resolve); child.kill('SIGKILL');
|
|
1888
|
-
}));
|
|
1889
|
-
await Promise.all(exits);
|
|
1890
|
-
}
|
|
1891
|
-
console.log(JSON.stringify(result));
|
|
1892
|
-
}
|
|
1893
|
-
JS
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
902
|
serena_workspace_prepare() {
|
|
1897
903
|
cat <<'PYTHON'
|
|
1898
904
|
import sys, os, json, pathlib, tempfile, fcntl
|
|
@@ -2172,7 +1178,7 @@ install_serena() {
|
|
|
2172
1178
|
Darwin) target=$cpu-apple-darwin ;;
|
|
2173
1179
|
*) die "managed Serena supports Linux and macOS, not $os" ;;
|
|
2174
1180
|
esac
|
|
2175
|
-
|
|
1181
|
+
validate_managed_tree_path "$gestalt_home/serena"
|
|
2176
1182
|
umask 077
|
|
2177
1183
|
mkdir -p -- "$gestalt_home/serena"
|
|
2178
1184
|
mkdir -- "$gestalt_home/serena/.install-lock" 2>/dev/null ||
|
|
@@ -3396,150 +2402,6 @@ for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { void clos
|
|
|
3396
2402
|
NODE
|
|
3397
2403
|
}
|
|
3398
2404
|
|
|
3399
|
-
command_xerj() {
|
|
3400
|
-
case ${1:-} in
|
|
3401
|
-
probe | ensure-ready | status | stop | __backend)
|
|
3402
|
-
local operation=$1
|
|
3403
|
-
shift
|
|
3404
|
-
command_xerj_readiness "$operation" "$@"
|
|
3405
|
-
return ;;
|
|
3406
|
-
esac
|
|
3407
|
-
load_xerj_paths
|
|
3408
|
-
if [[ ${1:-} == -- ]]; then shift; fi
|
|
3409
|
-
if [[ ${1:-} == install ]]; then
|
|
3410
|
-
(($# == 1)) || die 'usage: gestalt xerj install'
|
|
3411
|
-
update_xerj
|
|
3412
|
-
return
|
|
3413
|
-
fi
|
|
3414
|
-
if [[ ${1:-} == update ]]; then shift; update_xerj "$@"; return; fi
|
|
3415
|
-
if [[ ${1:-} == test ]]; then
|
|
3416
|
-
shift
|
|
3417
|
-
test_xerj "$@"
|
|
3418
|
-
return
|
|
3419
|
-
fi
|
|
3420
|
-
local mode=server variable escaped_config xerj_url xerj_api_key xerj_auth xerj_port
|
|
3421
|
-
local index_source='' index_prefix='' index_cwd=false index_status=false autoindex_state
|
|
3422
|
-
local -a forwarded=() xerj_launcher=()
|
|
3423
|
-
local -a xerj_user_args=()
|
|
3424
|
-
case ${1:-} in
|
|
3425
|
-
index | autoindex | search | def | gain | mcp) mode=$1; shift ;;
|
|
3426
|
-
'' | -*) ;;
|
|
3427
|
-
*) die "xerj command '$1' is not managed; init, brain/share, corpus/code, feedback, service, update and export can write outside managed state" ;;
|
|
3428
|
-
esac
|
|
3429
|
-
if [[ $mode == autoindex && ${1:-} == status ]]; then
|
|
3430
|
-
index_status=true
|
|
3431
|
-
shift
|
|
3432
|
-
fi
|
|
3433
|
-
xerj_url=${XERJ_URL:-}
|
|
3434
|
-
if [[ -z $xerj_url && -f $xerj_data/.lifecycle/endpoint.json ]]; then
|
|
3435
|
-
require_command node
|
|
3436
|
-
xerj_url=$(node -e 'const fs=require("node:fs"); const record=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); if(record.schemaVersion!==1 || typeof record.endpoint!=="string") process.exit(1); process.stdout.write(record.endpoint);' "$xerj_data/.lifecycle/endpoint.json") || die 'invalid managed xerj endpoint'
|
|
3437
|
-
fi
|
|
3438
|
-
validate_xerj_url "${xerj_url:-http://127.0.0.1:9200}"
|
|
3439
|
-
xerj_url=$validated_xerj_url
|
|
3440
|
-
xerj_port=$validated_xerj_port
|
|
3441
|
-
if [[ -n ${XERJ_BIND_ADDRESS:-} ]]; then validate_xerj_bind "$XERJ_BIND_ADDRESS"; fi
|
|
3442
|
-
validate_xerj_arguments "$mode" "$@"
|
|
3443
|
-
if "$index_status"; then
|
|
3444
|
-
index_source=${index_source:-$(pwd -P)}
|
|
3445
|
-
xerj_user_args=(status "${xerj_user_args[@]}")
|
|
3446
|
-
fi
|
|
3447
|
-
autoindex_state=$xerj_autoindex_home
|
|
3448
|
-
if [[ $mode == autoindex && -n $index_source && $index_source != map && $index_source != status ]]; then
|
|
3449
|
-
if [[ -z $index_prefix ]]; then
|
|
3450
|
-
require_command node
|
|
3451
|
-
index_prefix=$(node -e 'const {realpathSync}=require("node:fs"); const {createHash}=require("node:crypto"); process.stdout.write("ax-"+createHash("sha256").update(/^(s3|r2):\/\//.test(process.argv[1]) ? process.argv[1].replace(/\/+$/, "") : realpathSync(process.argv[1])).digest("hex").slice(0,16));' "$index_source")
|
|
3452
|
-
xerj_user_args+=(--prefix "$index_prefix")
|
|
3453
|
-
fi
|
|
3454
|
-
[[ $index_prefix =~ ^[a-z0-9][a-z0-9_-]{0,79}$ ]] || die 'xerj index prefix must be a lowercase index name (maximum 80 characters)'
|
|
3455
|
-
autoindex_state=$autoindex_state/$index_prefix
|
|
3456
|
-
fi
|
|
3457
|
-
if "$index_status"; then
|
|
3458
|
-
# The native status reader needs the same destination as the watcher.
|
|
3459
|
-
# It otherwise uses its own default port, even with XERJ_URL set.
|
|
3460
|
-
local status_url=false status_argument
|
|
3461
|
-
for status_argument in "${xerj_user_args[@]}"; do
|
|
3462
|
-
if [[ $status_argument == --url ]]; then status_url=true; fi
|
|
3463
|
-
done
|
|
3464
|
-
if ! "$status_url"; then xerj_user_args+=(--url "$xerj_url"); fi
|
|
3465
|
-
fi
|
|
3466
|
-
for variable in XERJ_CONFIG XERJ_INGEST_MEMORY_OUTPUT XERJ_DEBUG_PROFILE_DIR XERJ_PDF_WORKER_BIN XERJ_NEURAL_LOCAL_DIR XERJ_DECIDE_MODEL_DIR XERJ_ONNX_MODEL XERJ_ONNX_TOKENIZER XERJ_CODE_HOME; do
|
|
3467
|
-
[[ -z ${!variable:-} ]] || die "unset $variable before running managed xerj; inherited path overrides are not accepted"
|
|
3468
|
-
done
|
|
3469
|
-
[[ -x $xerj_bin && -f $xerj_bin ]] || die "xerj is not installed; run 'gestalt xerj install'"
|
|
3470
|
-
if [[ $mode == server ]] && (($# == 1)) && [[ $1 == -V || $1 == --version ]]; then
|
|
3471
|
-
# Version discovery must not create configuration or require writable state.
|
|
3472
|
-
env -i PATH="$PATH" XERJ_INSTALL_DIR="$xerj_root" "$xerj_bin" -V
|
|
3473
|
-
return
|
|
3474
|
-
fi
|
|
3475
|
-
xerj_api_key=${XERJ_API_KEY:-}
|
|
3476
|
-
if [[ -z $xerj_api_key && -f $xerj_data/admin.key ]]; then
|
|
3477
|
-
xerj_api_key=$(< "$xerj_data/admin.key")
|
|
3478
|
-
fi
|
|
3479
|
-
xerj_auth=${XERJ_AUTH:-}
|
|
3480
|
-
if [[ -z $xerj_auth ]]; then
|
|
3481
|
-
# A nonempty explicit header prevents upstream guessing keys in HOME/cwd.
|
|
3482
|
-
xerj_auth="ApiKey ${xerj_api_key:-managed-key-unavailable}"
|
|
3483
|
-
fi
|
|
3484
|
-
umask 077
|
|
3485
|
-
trap 'exit 130' INT
|
|
3486
|
-
trap 'exit 143' TERM
|
|
3487
|
-
if ! "$index_status"; then
|
|
3488
|
-
mkdir -p -- "$xerj_data/tmp" "$xerj_data/cache" "$xerj_data/config" "$xerj_data/share"
|
|
3489
|
-
escaped_config=${xerj_data//\\/\\\\}
|
|
3490
|
-
escaped_config=${escaped_config//\"/\\\"}
|
|
3491
|
-
xerj_config_scratch=$(mktemp "$xerj_data/.config.XXXXXXXX")
|
|
3492
|
-
printf '[embedding]\nmodel_cache_dir = "%s/cache/huggingface"\n[tls]\ncert_path = "%s/xerj.crt"\nkey_path = "%s/xerj.key"\n' \
|
|
3493
|
-
"$escaped_config" "$escaped_config" "$escaped_config" > "$xerj_config_scratch"
|
|
3494
|
-
mv -f -- "$xerj_config_scratch" "$xerj_data/managed.toml"
|
|
3495
|
-
xerj_config_scratch=''
|
|
3496
|
-
fi
|
|
3497
|
-
case $mode in
|
|
3498
|
-
server) forwarded=(--config "$xerj_data/managed.toml" --data-dir "$xerj_data" --bind "${XERJ_BIND_ADDRESS:-127.0.0.1}") ;;
|
|
3499
|
-
index) forwarded=(index --config "$xerj_data/managed.toml" --data-dir "$xerj_data") ;;
|
|
3500
|
-
autoindex) forwarded=(autoindex --state-dir "$autoindex_state") ;;
|
|
3501
|
-
*) forwarded=("$mode") ;;
|
|
3502
|
-
esac
|
|
3503
|
-
if [[ $mode == server ]]; then
|
|
3504
|
-
local explicit_port=false argument
|
|
3505
|
-
for argument in "${xerj_user_args[@]}"; do
|
|
3506
|
-
if [[ $argument == --port ]]; then explicit_port=true; fi
|
|
3507
|
-
done
|
|
3508
|
-
if ! "$explicit_port"; then forwarded+=(--port "$xerj_port"); fi
|
|
3509
|
-
fi
|
|
3510
|
-
local watch_requested=false watch_argument
|
|
3511
|
-
for watch_argument in "${xerj_user_args[@]}"; do
|
|
3512
|
-
if [[ $watch_argument == --watch ]]; then watch_requested=true; fi
|
|
3513
|
-
done
|
|
3514
|
-
if [[ $mode == autoindex ]] && "$watch_requested"; then
|
|
3515
|
-
check_xerj_watch_layout "$index_source" "$autoindex_state" || return 1
|
|
3516
|
-
require_command flock
|
|
3517
|
-
require_command setpriv
|
|
3518
|
-
mkdir -p -- "$autoindex_state"
|
|
3519
|
-
# Native journal locking covers a pass, not the idle watcher lifetime.
|
|
3520
|
-
# No PID file: the kernel releases this lock even after an abrupt exit.
|
|
3521
|
-
xerj_launcher=(flock --nonblock --conflict-exit-code 75 --no-fork "$autoindex_state/.gestalt-watch.lock" setpriv --pdeathsig TERM --)
|
|
3522
|
-
fi
|
|
3523
|
-
local -a xerj_temporary_environment=(TMPDIR="$xerj_data/tmp" TMP="$xerj_data/tmp" TEMP="$xerj_data/tmp")
|
|
3524
|
-
# The shared backend must never borrow a calling session's owner. Its service
|
|
3525
|
-
# lifetime is independent; client/index/MCP work retains the validated context.
|
|
3526
|
-
if [[ $mode != server || $session_tmp_owner_kind == workspace-service ]]; then
|
|
3527
|
-
xerj_temporary_environment=(TMPDIR="${TMPDIR:-$xerj_data/tmp}" TMP="${TMP:-${TMPDIR:-$xerj_data/tmp}}" TEMP="${TEMP:-${TMPDIR:-$xerj_data/tmp}}")
|
|
3528
|
-
if [[ ${GESTALT_SESSION_TMP_CONTEXT+x} ]]; then
|
|
3529
|
-
xerj_temporary_environment+=(GESTALT_SESSION_TMP_CONTEXT="$GESTALT_SESSION_TMP_CONTEXT")
|
|
3530
|
-
fi
|
|
3531
|
-
fi
|
|
3532
|
-
# Preserve HOME, streams and exit/signal identity; use known environment inputs.
|
|
3533
|
-
# These settings route automatic state. They do not sandbox server API writes.
|
|
3534
|
-
exec "${xerj_launcher[@]}" env -i HOME="$HOME" PATH="$PATH" GESTALT_HOME="$gestalt_home" CODEX_HOME="$codex_home" \
|
|
3535
|
-
XERJ_INSTALL_DIR="$xerj_root" XERJ_API_KEY="$xerj_api_key" XERJ_AUTH="$xerj_auth" XERJ_URL="$xerj_url" \
|
|
3536
|
-
XERJ_CODE_HOME="$xerj_data/code" \
|
|
3537
|
-
XERJ_LOG="${XERJ_LOG:-info}" XERJ_DISABLE_FEEDBACK="${XERJ_DISABLE_FEEDBACK:-false}" \
|
|
3538
|
-
XDG_CACHE_HOME="$xerj_data/cache" XDG_CONFIG_HOME="$xerj_data/config" XDG_DATA_HOME="$xerj_data/share" \
|
|
3539
|
-
HF_HOME="$xerj_data/cache/huggingface" "${xerj_temporary_environment[@]}" \
|
|
3540
|
-
LANG="${LANG:-C}" TERM="${TERM:-dumb}" "$xerj_bin" "${forwarded[@]}" "${xerj_user_args[@]}"
|
|
3541
|
-
}
|
|
3542
|
-
|
|
3543
2405
|
require_command() {
|
|
3544
2406
|
local -r command_name=$1
|
|
3545
2407
|
command -v "$command_name" >/dev/null 2>&1 ||
|
|
@@ -4476,40 +3338,48 @@ configure_codex_permissions() {
|
|
|
4476
3338
|
local -r config_path=$codex_home/config.toml
|
|
4477
3339
|
|
|
4478
3340
|
node --input-type=module - \
|
|
4479
|
-
"$config_path" "$codex_home" "$gestalt_home" "$HOME/.agents" \
|
|
3341
|
+
"$config_path" "${BASH_SOURCE[0]}" "$codex_home" "$gestalt_home" "$HOME/.agents" \
|
|
4480
3342
|
"$HOME/.local" "$HOME/.config" <<'NODE'
|
|
4481
3343
|
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
4482
3344
|
import { dirname } from 'node:path';
|
|
3345
|
+
import { runInNewContext } from 'node:vm';
|
|
4483
3346
|
|
|
4484
3347
|
const configPath = process.argv[2];
|
|
4485
|
-
const
|
|
3348
|
+
const managerPath = process.argv[3];
|
|
3349
|
+
const homeReadRoots = [...new Set(process.argv.slice(4))];
|
|
3350
|
+
const bundle = readFileSync(managerPath, 'utf8').match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
|
|
3351
|
+
if (!bundle) throw new Error('Bundled TOML parser missing');
|
|
3352
|
+
const { parse } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
|
|
4486
3353
|
const source = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
|
|
4487
|
-
|
|
3354
|
+
parse(source); // Reject invalid input before any replacement is staged.
|
|
3355
|
+
const newline = source.match(/\r\n|\n|\r/)?.[0] ?? '\n';
|
|
4488
3356
|
const retained = [];
|
|
4489
|
-
let
|
|
3357
|
+
let rootSection = true;
|
|
4490
3358
|
let removingSection = false;
|
|
4491
|
-
|
|
4492
|
-
|
|
4493
|
-
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
3359
|
+
let permissionsPosition;
|
|
3360
|
+
let statement = '';
|
|
3361
|
+
// Complete TOML statements keep multiline strings/arrays opaque. Retain raw
|
|
3362
|
+
// comment, whitespace and unrelated statement bytes, including mixed newlines.
|
|
3363
|
+
for (const line of source.match(/[^\r\n]*(?:\r\n|\n|\r|$)/g) ?? []) {
|
|
3364
|
+
if (!line) continue;
|
|
3365
|
+
statement += line;
|
|
3366
|
+
let parsed;
|
|
3367
|
+
try { parsed = parse(statement); } catch { continue; }
|
|
3368
|
+
const current = statement;
|
|
3369
|
+
statement = '';
|
|
3370
|
+
if (/^[ \t]*\[/.test(current)) {
|
|
3371
|
+
rootSection = false;
|
|
3372
|
+
removingSection = Boolean(parsed.sandbox_workspace_write || parsed.permissions?.['workspace-git']);
|
|
3373
|
+
if (removingSection) {
|
|
3374
|
+
permissionsPosition ??= retained.length;
|
|
3375
|
+
continue;
|
|
3376
|
+
}
|
|
4501
3377
|
}
|
|
4502
|
-
if (removingSection) continue;
|
|
4503
|
-
if (
|
|
4504
|
-
|
|
4505
|
-
/^\s*(?:approval_policy|default_permissions|sandbox_mode)\s*=/.test(line)
|
|
4506
|
-
)
|
|
4507
|
-
continue;
|
|
4508
|
-
retained.push(line);
|
|
3378
|
+
if (removingSection && Object.keys(parsed).length) continue;
|
|
3379
|
+
if (rootSection && ['approval_policy', 'default_permissions', 'sandbox_mode'].some(key => Object.hasOwn(parsed, key))) continue;
|
|
3380
|
+
retained.push(current);
|
|
4509
3381
|
}
|
|
4510
|
-
|
|
4511
|
-
while (retained.length > 0 && retained[0].trim() === '') retained.shift();
|
|
4512
|
-
while (retained.length > 0 && retained.at(-1).trim() === '') retained.pop();
|
|
3382
|
+
if (statement) throw new Error('Could not safely localize permissions configuration');
|
|
4513
3383
|
|
|
4514
3384
|
const root = [
|
|
4515
3385
|
'approval_policy = "never"',
|
|
@@ -4535,7 +3405,15 @@ const profile = [
|
|
|
4535
3405
|
'".agents" = "read"',
|
|
4536
3406
|
'".codex" = "read"',
|
|
4537
3407
|
];
|
|
4538
|
-
const
|
|
3408
|
+
const position = permissionsPosition ?? retained.length;
|
|
3409
|
+
let before = retained.slice(0, position).join('');
|
|
3410
|
+
if (before && !/[\r\n]$/.test(before)) before += newline;
|
|
3411
|
+
// Keep the replacement at the original owned-table boundary. Moving it past
|
|
3412
|
+
// another setup writer's table would strand that writer's separator on repeats.
|
|
3413
|
+
// Existing comments/blank lines stay intact; generated tables add no new gaps.
|
|
3414
|
+
const output = root.join(newline) + newline + before +
|
|
3415
|
+
profile.filter(line => line !== '').join(newline) + newline + retained.slice(position).join('');
|
|
3416
|
+
parse(output);
|
|
4539
3417
|
if (output === source) process.exit(0);
|
|
4540
3418
|
|
|
4541
3419
|
mkdirSync(dirname(configPath), { recursive: true });
|
|
@@ -4794,6 +3672,105 @@ command_agents() {
|
|
|
4794
3672
|
esac
|
|
4795
3673
|
}
|
|
4796
3674
|
|
|
3675
|
+
# Retire configuration only when its executable and complete argument contract
|
|
3676
|
+
# prove ownership. Old processes, indexes, binaries and bare restart records
|
|
3677
|
+
# have no transferable ownership proof; preserve them for operator inspection.
|
|
3678
|
+
retire_managed_xerj() {
|
|
3679
|
+
node --input-type=module - "$codex_home" "$gestalt_home" "${BASH_SOURCE[0]}" <<'NODE'
|
|
3680
|
+
import { readFileSync, readdirSync, lstatSync, realpathSync, openSync, writeFileSync, fchmodSync, fsyncSync, closeSync, renameSync, unlinkSync } from 'node:fs';
|
|
3681
|
+
import { join, dirname } from 'node:path';
|
|
3682
|
+
import { randomBytes } from 'node:crypto';
|
|
3683
|
+
import { runInNewContext } from 'node:vm';
|
|
3684
|
+
const [selectedCodex, selectedHome, manager] = process.argv.slice(2);
|
|
3685
|
+
const source = readFileSync(manager, 'utf8');
|
|
3686
|
+
const bundle = source.match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
|
|
3687
|
+
if (!bundle) throw new Error('Bundled TOML parser missing');
|
|
3688
|
+
const { parse } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
|
|
3689
|
+
const notices = new Set();
|
|
3690
|
+
const notice = kind => notices.add(kind);
|
|
3691
|
+
const exists = path => { try { return lstatSync(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
|
3692
|
+
const canonical = path => { try { return realpathSync(path); } catch { return null; } };
|
|
3693
|
+
const codex = canonical(selectedCodex), home = canonical(selectedHome), executable = canonical(manager);
|
|
3694
|
+
// Home aliases are allowed. Descendant links/hardlinks are never write targets.
|
|
3695
|
+
const plain = path => {
|
|
3696
|
+
const info = exists(path);
|
|
3697
|
+
return info?.isFile() && info.nlink === 1 && (!process.getuid || info.uid === process.getuid()) ? info : null;
|
|
3698
|
+
};
|
|
3699
|
+
const owned = server => server && !server.url && typeof server.command === 'string' &&
|
|
3700
|
+
server.command.startsWith('/') && canonical(server.command) === executable &&
|
|
3701
|
+
Array.isArray(server.args) && JSON.stringify(server.args) === '["xerj","mcp"]';
|
|
3702
|
+
const related = (name, server) => /xerj/i.test(name) || server?.args?.[0] === 'xerj';
|
|
3703
|
+
const stable = value => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
|
|
3704
|
+
? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
|
|
3705
|
+
function migrate(path) {
|
|
3706
|
+
if (!exists(path)) return;
|
|
3707
|
+
const info = plain(path);
|
|
3708
|
+
if (!info) { notice('configuration'); return; }
|
|
3709
|
+
const bytes = readFileSync(path, 'utf8');
|
|
3710
|
+
let config;
|
|
3711
|
+
try { config = parse(bytes); } catch { notice('configuration'); return; }
|
|
3712
|
+
const names = Object.entries(config.mcp_servers ?? {}).filter(([name, server]) => {
|
|
3713
|
+
if (owned(server)) return true;
|
|
3714
|
+
if (related(name, server)) notice('configuration');
|
|
3715
|
+
return false;
|
|
3716
|
+
}).map(([name]) => name);
|
|
3717
|
+
if (!names.length) return;
|
|
3718
|
+
const expected = structuredClone(config);
|
|
3719
|
+
for (const name of names) delete expected.mcp_servers[name];
|
|
3720
|
+
// Preserve physical bytes of every unrelated section and every standalone
|
|
3721
|
+
// comment. Validate the entire semantic result before committing any edit;
|
|
3722
|
+
// inline/dotted or multiline constructs that cannot be localized stay intact.
|
|
3723
|
+
let removing = false;
|
|
3724
|
+
const output = bytes.split(/(?<=\n)/).filter(line => {
|
|
3725
|
+
if (/^[ \t]*\[/.test(line)) {
|
|
3726
|
+
removing = false;
|
|
3727
|
+
try {
|
|
3728
|
+
const table = parse(line + '\n__gestalt_retirement_marker = true\n');
|
|
3729
|
+
removing = names.some(name => table.mcp_servers?.[name]);
|
|
3730
|
+
} catch { /* Whole-result validation below rejects uncertain edits. */ }
|
|
3731
|
+
}
|
|
3732
|
+
return !removing || line.trim() === '' || /^[ \t]*#/.test(line);
|
|
3733
|
+
}).join('');
|
|
3734
|
+
// TOML does not retain empty implicit parent tables after removing children.
|
|
3735
|
+
if (!Object.keys(expected.mcp_servers).length) delete expected.mcp_servers;
|
|
3736
|
+
try { if (stable(parse(output)) !== stable(expected)) { notice('configuration'); return; } }
|
|
3737
|
+
catch { notice('configuration'); return; }
|
|
3738
|
+
if (bytes === output) return;
|
|
3739
|
+
const temporary = join(dirname(path), '.gestalt-retirement-' + randomBytes(12).toString('hex'));
|
|
3740
|
+
let handle;
|
|
3741
|
+
try {
|
|
3742
|
+
handle = openSync(temporary, 'wx', 0o600);
|
|
3743
|
+
writeFileSync(handle, output); fchmodSync(handle, info.mode & 0o777); fsyncSync(handle);
|
|
3744
|
+
closeSync(handle); handle = undefined;
|
|
3745
|
+
const current = plain(path);
|
|
3746
|
+
if (!current || current.dev !== info.dev || current.ino !== info.ino || readFileSync(path, 'utf8') !== bytes)
|
|
3747
|
+
throw new Error('configuration changed during Xerj retirement; retry update');
|
|
3748
|
+
renameSync(temporary, path);
|
|
3749
|
+
} finally {
|
|
3750
|
+
if (handle !== undefined) closeSync(handle);
|
|
3751
|
+
try { unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
if (codex) {
|
|
3755
|
+
for (const name of readdirSync(codex).sort())
|
|
3756
|
+
if (name === 'config.toml' || /^[a-zA-Z0-9_-]+\.config\.toml$/.test(name)) migrate(join(codex, name));
|
|
3757
|
+
// No PID, socket, endpoint or record alone proves a live process belongs to
|
|
3758
|
+
// this updater. Do not probe it, send signals, or delete persistent data.
|
|
3759
|
+
if (exists(join(codex, 'xerj-data', '.lifecycle'))) notice('process records');
|
|
3760
|
+
}
|
|
3761
|
+
if (home && exists(join(home, 'run'))) {
|
|
3762
|
+
const run = join(home, 'run');
|
|
3763
|
+
if (!exists(run).isDirectory()) notice('restart descriptors');
|
|
3764
|
+
else for (const name of readdirSync(run)) if (/^mobile-[1-9][0-9]*\.restart$/.test(name)) {
|
|
3765
|
+
const file = join(run, name);
|
|
3766
|
+
if (!plain(file)) { notice('restart descriptors'); continue; }
|
|
3767
|
+
if (readFileSync(file).includes(Buffer.from('--xerj'))) notice('restart descriptors');
|
|
3768
|
+
}
|
|
3769
|
+
}
|
|
3770
|
+
for (const kind of notices) process.stderr.write(`gestalt: Xerj retirement: ${kind} preserved; review legacy Xerj entries/processes manually, then retry update. User data and binaries are retained.\n`);
|
|
3771
|
+
NODE
|
|
3772
|
+
}
|
|
3773
|
+
|
|
4797
3774
|
command_install() {
|
|
4798
3775
|
parse_setup_options "$@"
|
|
4799
3776
|
command_skills install
|
|
@@ -4803,13 +3780,11 @@ command_install() {
|
|
|
4803
3780
|
}
|
|
4804
3781
|
|
|
4805
3782
|
command_update() {
|
|
4806
|
-
# XERJ canonicalizes these paths. Keep that normalization local so a live
|
|
4807
|
-
# Mobile restart descriptor retains the path spelling used at launch.
|
|
4808
|
-
local gestalt_home=$gestalt_home codex_home=$codex_home
|
|
4809
3783
|
parse_update_options "$@"
|
|
4810
3784
|
case $update_component in
|
|
4811
3785
|
all | gestalt)
|
|
4812
3786
|
update_manager
|
|
3787
|
+
retire_managed_xerj
|
|
4813
3788
|
command_skills update
|
|
4814
3789
|
run_marketplace_setup upgrade "$include_extra_skills"
|
|
4815
3790
|
install_mobile
|
|
@@ -4826,12 +3801,6 @@ command_update() {
|
|
|
4826
3801
|
elif [[ $update_component == all ]]; then
|
|
4827
3802
|
log 'skipping Serena (not installed; use gestalt update serena to install)'
|
|
4828
3803
|
fi
|
|
4829
|
-
if [[ $update_component == xerj || ( $update_component == all && -e $gestalt_home/xerj/xerj ) ]]; then
|
|
4830
|
-
log 'updating XERJ'
|
|
4831
|
-
command_xerj update
|
|
4832
|
-
elif [[ $update_component == all ]]; then
|
|
4833
|
-
log 'skipping XERJ (not installed; use gestalt update xerj to install)'
|
|
4834
|
-
fi
|
|
4835
3804
|
if [[ $update_component == playwright || ( $update_component == all && -f $gestalt_home/playwright/active.json ) ]]; then
|
|
4836
3805
|
command_playwright update
|
|
4837
3806
|
elif [[ $update_component == all ]]; then
|
|
@@ -4846,16 +3815,17 @@ parse_update_options() {
|
|
|
4846
3815
|
local component_selected=false
|
|
4847
3816
|
while (($# > 0)); do
|
|
4848
3817
|
case $1 in
|
|
3818
|
+
xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
|
|
4849
3819
|
--extra-skills) include_extra_skills=true ;;
|
|
4850
3820
|
-h | --help) usage; exit 0 ;;
|
|
4851
3821
|
--component)
|
|
4852
|
-
(($# >= 2)) || die '--component requires all, gestalt, serena,
|
|
3822
|
+
(($# >= 2)) || die '--component requires all, gestalt, serena, or playwright'
|
|
4853
3823
|
[[ $component_selected == false ]] || die 'select only one update component'
|
|
4854
3824
|
update_component=$2
|
|
4855
3825
|
component_selected=true
|
|
4856
3826
|
shift
|
|
4857
3827
|
;;
|
|
4858
|
-
all | gestalt | serena |
|
|
3828
|
+
all | gestalt | serena | playwright)
|
|
4859
3829
|
[[ $component_selected == false ]] || die 'select only one update component'
|
|
4860
3830
|
update_component=$1
|
|
4861
3831
|
component_selected=true
|
|
@@ -4865,8 +3835,9 @@ parse_update_options() {
|
|
|
4865
3835
|
shift
|
|
4866
3836
|
done
|
|
4867
3837
|
case $update_component in
|
|
4868
|
-
|
|
4869
|
-
|
|
3838
|
+
xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
|
|
3839
|
+
all | gestalt | serena | playwright) ;;
|
|
3840
|
+
*) die "unknown update component: $update_component (choose all, gestalt, serena, or playwright)" ;;
|
|
4870
3841
|
esac
|
|
4871
3842
|
[[ $include_extra_skills == false || $update_component == all || $update_component == gestalt ]] ||
|
|
4872
3843
|
die '--extra-skills requires the all or gestalt update component'
|
|
@@ -4943,6 +3914,29 @@ command_update_restart() {
|
|
|
4943
3914
|
log "progress will be written to $restart_log; this session will reconnect after restart"
|
|
4944
3915
|
}
|
|
4945
3916
|
|
|
3917
|
+
# Old managers stored these options in NUL-delimited restart descriptors. Adapt
|
|
3918
|
+
# only the arguments consumed by this explicitly requested restart; unproven
|
|
3919
|
+
# records on disk remain untouched. Never reinterpret unknown retirement values.
|
|
3920
|
+
retire_mobile_restart_arguments() {
|
|
3921
|
+
migrated_restart_args=()
|
|
3922
|
+
while (($#)); do
|
|
3923
|
+
case $1 in
|
|
3924
|
+
--xerj)
|
|
3925
|
+
(($# >= 2)) || die 'legacy --xerj restart option has no value; review the restart descriptor before updating'
|
|
3926
|
+
case $2 in
|
|
3927
|
+
auto | manual | off) shift 2 ;;
|
|
3928
|
+
*) die 'legacy --xerj restart option is ambiguous; review the restart descriptor before updating' ;;
|
|
3929
|
+
esac
|
|
3930
|
+
;;
|
|
3931
|
+
--)
|
|
3932
|
+
migrated_restart_args+=("$@")
|
|
3933
|
+
break
|
|
3934
|
+
;;
|
|
3935
|
+
*) migrated_restart_args+=("$1"); shift ;;
|
|
3936
|
+
esac
|
|
3937
|
+
done
|
|
3938
|
+
}
|
|
3939
|
+
|
|
4946
3940
|
command_update_restart_worker() {
|
|
4947
3941
|
local -r relay_pid=${1:-}
|
|
4948
3942
|
local -r restart_state=${2:-}
|
|
@@ -4951,7 +3945,7 @@ command_update_restart_worker() {
|
|
|
4951
3945
|
local -r restart_lock=${5:-}
|
|
4952
3946
|
local -r worker_component=${6:-all}
|
|
4953
3947
|
local restart_cwd restart_field manager_target
|
|
4954
|
-
local -a restart_record restart_args update_args=()
|
|
3948
|
+
local -a restart_record restart_args migrated_restart_args update_args=()
|
|
4955
3949
|
|
|
4956
3950
|
[[ -n $restart_log ]] || die 'the update-restart worker log path is missing'
|
|
4957
3951
|
validate_managed_path 'update-restart log' "$restart_log"
|
|
@@ -4972,6 +3966,8 @@ command_update_restart_worker() {
|
|
|
4972
3966
|
((${#restart_record[@]} >= 1)) || die 'the Gestalt Mobile restart descriptor is empty'
|
|
4973
3967
|
restart_cwd=${restart_record[0]}
|
|
4974
3968
|
restart_args=("${restart_record[@]:1}")
|
|
3969
|
+
retire_mobile_restart_arguments "${restart_args[@]}"
|
|
3970
|
+
restart_args=("${migrated_restart_args[@]}")
|
|
4975
3971
|
[[ $restart_cwd == /* && -d $restart_cwd ]] ||
|
|
4976
3972
|
die "the Gestalt Mobile restart directory is invalid: $restart_cwd"
|
|
4977
3973
|
[[ $worker_extra_skills == false || $worker_extra_skills == true ]] ||
|
|
@@ -5013,7 +4009,7 @@ strip_separator() {
|
|
|
5013
4009
|
# startup gates the actual first turn; a failed optional connection retries with
|
|
5014
4010
|
# only that capability disabled. Serena semantics are verified on the first
|
|
5015
4011
|
# policy-bearing tool call. This is native Codex stdio, not an MCP bridge.
|
|
5016
|
-
|
|
4012
|
+
launch_cli_with_capabilities() {
|
|
5017
4013
|
CODEX_HOME="$codex_home" GESTALT_HOME="$gestalt_home" \
|
|
5018
4014
|
GESTALT_MANAGER_BIN="$manager_target" GESTALT_STARTUP_DIAGNOSTICS_DONE=1 \
|
|
5019
4015
|
PATH="$gestalt_home/bin:$codex_home/bin:$PATH" \
|
|
@@ -5033,7 +4029,7 @@ function managedToolApproval(server) {
|
|
|
5033
4029
|
}
|
|
5034
4030
|
function isGestaltManagedMcp(name, server, owner) {
|
|
5035
4031
|
if (!server || typeof server !== 'object' || server.url) return false;
|
|
5036
|
-
const components = {'gestalt-
|
|
4032
|
+
const components = {'gestalt-serena':'serena','gestalt-playwright':'playwright'};
|
|
5037
4033
|
if (Object.hasOwn(components,name)) return (!server.command && !server.args) ||
|
|
5038
4034
|
([owner.manager,'gestalt'].includes(server.command) && server.args?.[0] === components[name] && server.args?.[1] === 'mcp');
|
|
5039
4035
|
return name === 'context-mode' && String(server.command).split('/').at(-1) === 'node' &&
|
|
@@ -5127,7 +4123,6 @@ ${s}`:n||s}function $(e,{maxDepth:r=1e3,numbersAsFloat:i=!1,strictTemporal:t=!1}
|
|
|
5127
4123
|
`:a}return R(le);})();
|
|
5128
4124
|
// END BUNDLED PROFILE TOML PARSER
|
|
5129
4125
|
const args = process.argv.slice(2);
|
|
5130
|
-
const serverName = 'gestalt-xerj';
|
|
5131
4126
|
const manager = process.env.GESTALT_MANAGER_BIN;
|
|
5132
4127
|
const scratchNames=['GESTALT_SESSION_TMP_CONTEXT','TMPDIR','TMP','TEMP'];
|
|
5133
4128
|
const environment={...process.env};
|
|
@@ -5146,13 +4141,9 @@ const protectUnknownMapping=()=>{
|
|
|
5146
4141
|
if(cliOwned&&!mappingUnknown){mappingUnknown=true;scratchApi.scratchBorrow(JSON.parse(environment.GESTALT_SESSION_TMP_CONTEXT),'cli-provider-mapping-unknown');
|
|
5147
4142
|
process.stderr.write('gestalt: native provider association unavailable; CLI temporary owner remains protected\n');}
|
|
5148
4143
|
};
|
|
5149
|
-
const
|
|
5150
|
-
const budget = Number.isInteger(requested) && requested >= 100 && requested <= 60000 ? requested : 5000;
|
|
4144
|
+
const budget = 5000;
|
|
5151
4145
|
// One deadline covers native discovery, shared readiness and MCP startup.
|
|
5152
4146
|
let readinessDeadline = Date.now() + budget;
|
|
5153
|
-
const remainingTime = () => Math.max(0, readinessDeadline - Date.now());
|
|
5154
|
-
// A inherited hint is not evidence for a new or resumed runtime.
|
|
5155
|
-
delete environment.GESTALT_XERJ_READY;
|
|
5156
4147
|
let currentChild;
|
|
5157
4148
|
let playwrightController;
|
|
5158
4149
|
let interrupted = false;
|
|
@@ -5162,7 +4153,7 @@ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => {
|
|
|
5162
4153
|
interruptionCode = signal === 'SIGINT' ? 130 : 143;
|
|
5163
4154
|
currentChild?.kill(signal);
|
|
5164
4155
|
});
|
|
5165
|
-
const diagnose = reason => process.stderr.write(`gestalt:
|
|
4156
|
+
const diagnose = reason => process.stderr.write(`gestalt: capability discovery unavailable (${reason}); continuing with native tools\n`);
|
|
5166
4157
|
const toml = value => {
|
|
5167
4158
|
if (typeof value === 'string') return JSON.stringify(value);
|
|
5168
4159
|
if (Array.isArray(value)) return `[${value.map(toml).join(',')}]`;
|
|
@@ -5252,7 +4243,7 @@ async function snapshot(extra = [], hooksOnly = false, beforeFlags = false, dead
|
|
|
5252
4243
|
});
|
|
5253
4244
|
const timer = setTimeout(() => { fail(); child.kill(); }, Math.min(5000, remaining));
|
|
5254
4245
|
try {
|
|
5255
|
-
const initialized = await request('initialize', { clientInfo: { name: 'gestalt-
|
|
4246
|
+
const initialized = await request('initialize', { clientInfo: { name: 'gestalt-capability-config', version: '1' }, capabilities: {} });
|
|
5256
4247
|
child.stdin.write(`${JSON.stringify({ method: 'initialized', params: {} })}\n`);
|
|
5257
4248
|
if (hooksOnly) return await request('hooks/list', { cwds: [cwd] });
|
|
5258
4249
|
const config = await request('config/read', { cwd, includeLayers: true });
|
|
@@ -5269,24 +4260,6 @@ async function snapshot(extra = [], hooksOnly = false, beforeFlags = false, dead
|
|
|
5269
4260
|
}
|
|
5270
4261
|
}
|
|
5271
4262
|
|
|
5272
|
-
async function readiness(timeout) {
|
|
5273
|
-
timeout = Math.min(timeout, remainingTime());
|
|
5274
|
-
if (!timeout) return { status: 'unavailable', reason: 'readiness-deadline' };
|
|
5275
|
-
const selectedWorkspace=environment.GESTALT_SESSION_TMP_CONTEXT?JSON.parse(environment.GESTALT_SESSION_TMP_CONTEXT).workspacePath:null;
|
|
5276
|
-
const child = spawn(manager, ['xerj', 'ensure-ready',...(selectedWorkspace?['--cwd',selectedWorkspace]:[])], { cwd, env: {
|
|
5277
|
-
...discoveryEnvironment, XERJ_READY_TIMEOUT_MS: String(timeout),
|
|
5278
|
-
}, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
5279
|
-
currentChild = child;
|
|
5280
|
-
let output = '';
|
|
5281
|
-
child.stdout.on('data', data => { if (output.length < 32768) output += data; });
|
|
5282
|
-
const timer = setTimeout(() => child.kill(), timeout);
|
|
5283
|
-
try {
|
|
5284
|
-
const code = await new Promise(resolve => { child.once('error', () => resolve(-1)); child.once('exit', resolve); });
|
|
5285
|
-
if (code !== 0) return { status: 'unavailable', reason: 'manager-unavailable' };
|
|
5286
|
-
try { return JSON.parse(output); } catch { return { status: 'unavailable', reason: 'invalid-readiness' }; }
|
|
5287
|
-
} finally { clearTimeout(timer); currentChild = undefined; }
|
|
5288
|
-
}
|
|
5289
|
-
|
|
5290
4263
|
async function launch(launchArgs) {
|
|
5291
4264
|
if (playwrightController) return playwrightController(launchArgs);
|
|
5292
4265
|
const child = spawn('codex', launchArgs, { cwd: process.cwd(), env: environment,
|
|
@@ -5301,7 +4274,7 @@ async function launch(launchArgs) {
|
|
|
5301
4274
|
tail = (tail + data.toString()).slice(-8192);
|
|
5302
4275
|
// Scope names to the required-failure diagnostic, not unrelated stderr.
|
|
5303
4276
|
for (const diagnostic of tail.matchAll(/required MCP servers failed to initialize:([^\r\n]*)/g))
|
|
5304
|
-
for (const name of ['gestalt-
|
|
4277
|
+
for (const name of ['gestalt-serena'])
|
|
5305
4278
|
if (new RegExp(`(?:^|[\\s,;])${name}:`).test(diagnostic[1])) startupFailed.add(name);
|
|
5306
4279
|
});
|
|
5307
4280
|
const result = await new Promise(resolve => {
|
|
@@ -5357,23 +4330,11 @@ async function resolveNamedProfile(state, deadline = readinessDeadline, includeS
|
|
|
5357
4330
|
return state;
|
|
5358
4331
|
}
|
|
5359
4332
|
try { state = await resolveNamedProfile(state); } catch { state = undefined; diagnose('profile-discovery-unavailable'); }
|
|
5360
|
-
let skill = state?.skills.find(skill => skill.name === 'gestalt:xerj');
|
|
5361
4333
|
const session = state?.layers?.find(layer => layer.name?.type === 'sessionFlags')?.config ?? {};
|
|
5362
4334
|
let rules = session.skills?.config ?? explicitSkills?.config ?? [];
|
|
5363
4335
|
if (!Array.isArray(rules)) rules = [];
|
|
5364
4336
|
// Preserve unrelated selectors from effective config and user session flags.
|
|
5365
4337
|
const servers = state?.config?.mcp_servers ?? {};
|
|
5366
|
-
const duplicateNames = Object.entries(servers).filter(([name, config]) => name !== serverName &&
|
|
5367
|
-
config.command === manager && config.args?.[0] === 'xerj' && config.args?.[1] === 'mcp').map(([name]) => name);
|
|
5368
|
-
// Native dotted -c paths do not decode quoted key segments. A sparse
|
|
5369
|
-
// session table merges natively with existing servers, preserving their
|
|
5370
|
-
// credentials and settings without copying secrets into command arguments.
|
|
5371
|
-
const aliases = duplicateNames.length ? [`mcp_servers=${toml(Object.fromEntries(duplicateNames
|
|
5372
|
-
.map(name => [name, { enabled: false }])))}`] : [];
|
|
5373
|
-
const reserved = state?.config?.mcp_servers?.[serverName];
|
|
5374
|
-
const conflict = reserved && ((reserved.env && Object.keys(reserved.env).length) || reserved.enabled_tools ||
|
|
5375
|
-
reserved.disabled_tools?.length || reserved.tools && Object.keys(reserved.tools).length);
|
|
5376
|
-
const inactiveNotice = '<gestalt_xerj_unavailable>\nXerj retrieval is unavailable in this runtime. Earlier capability guidance is inactive; use rg and current source reads.\n</gestalt_xerj_unavailable>';
|
|
5377
4338
|
const shQuote = value => "'" + value.replaceAll("'", "'\\'" + "'") + "'";
|
|
5378
4339
|
const hookCommands = new Set();
|
|
5379
4340
|
let startupHook;
|
|
@@ -5399,7 +4360,7 @@ async function trustedHooks(selected) {
|
|
|
5399
4360
|
for (const hook of owned) trust[hook.key] = { ...trust[hook.key], enabled: true, trusted_hash: hook.currentHash };
|
|
5400
4361
|
return [...selected, `hooks.state=${toml(trust)}`];
|
|
5401
4362
|
}
|
|
5402
|
-
// Compose
|
|
4363
|
+
// Compose retained capabilities through the native discovery and hook path.
|
|
5403
4364
|
// The outer Serena catalog is connection evidence only. Its backend receives
|
|
5404
4365
|
// effective permissions on the first native tool call, never from this bootstrap.
|
|
5405
4366
|
const serenaName = 'gestalt-serena';
|
|
@@ -5410,10 +4371,8 @@ const serenaConflict = serenaReserved && (serenaReserved.env && Object.keys(sere
|
|
|
5410
4371
|
Object.values(serenaReserved.tools ?? {}).some(tool => tool.enabled !== undefined));
|
|
5411
4372
|
const serenaAliases = Object.entries(servers).filter(([name, config]) => name !== serenaName &&
|
|
5412
4373
|
config.command === manager && config.args?.[0] === 'serena' && config.args?.[1] === 'mcp').map(([name]) => name);
|
|
5413
|
-
|
|
5414
|
-
const capabilities = [{ name:
|
|
5415
|
-
config: { command: manager, args: ['xerj', 'mcp'] } },
|
|
5416
|
-
{ name: serenaName, skillName: 'gestalt:serena', skill: serenaSkill, valid: false,
|
|
4374
|
+
const aliases = serenaAliases.length ? [`mcp_servers=${toml(Object.fromEntries(serenaAliases.map(name => [name, { enabled: false }])))}`] : [];
|
|
4375
|
+
const capabilities = [{ name: serenaName, skillName: 'gestalt:serena', skill: serenaSkill, valid: false,
|
|
5417
4376
|
context: '<gestalt_serena_unavailable>\nSerena is unavailable in this runtime. Earlier Serena guidance is inactive; use native code tools.\n</gestalt_serena_unavailable>',
|
|
5418
4377
|
config: { command: manager, args: ['serena', 'mcp', '--cwd', cwd] } }];
|
|
5419
4378
|
for (const cap of capabilities) cap.inactiveContext = cap.context;
|
|
@@ -5558,8 +4517,12 @@ async function managedPlaywright(launchArgs, reportDiagnostic = () => {}, checkC
|
|
|
5558
4517
|
const {constants} = await import('node:fs');
|
|
5559
4518
|
const {join} = await import('node:path');
|
|
5560
4519
|
const endpoint = join(directory, 'frontend.sock');
|
|
5561
|
-
|
|
4520
|
+
const capacity = ({linux:108,darwin:104})[process.platform];
|
|
4521
|
+
if (!capacity) throw new Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
|
|
4522
|
+
if (Buffer.byteLength(endpoint) + 1 <= capacity)
|
|
5562
4523
|
return {endpoint, address:endpoint, close:async () => {}};
|
|
4524
|
+
if (process.platform !== 'linux')
|
|
4525
|
+
throw new Error('UNIX_SOCKET_PATH_TOO_LONG: use a bounded managed runtime root or shorten the endpoint name');
|
|
5563
4526
|
const handle = await fs.open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
5564
4527
|
try {
|
|
5565
4528
|
const info = await handle.stat();
|
|
@@ -5569,6 +4532,8 @@ async function managedPlaywright(launchArgs, reportDiagnostic = () => {}, checkC
|
|
|
5569
4532
|
// Keep the actual socket in its private owner. Linux resolves this short
|
|
5570
4533
|
// descriptor address to that same directory for bind and native connect.
|
|
5571
4534
|
const address = `/proc/${process.pid}/fd/${handle.fd}/frontend.sock`;
|
|
4535
|
+
if (Buffer.byteLength(address) + 1 > capacity)
|
|
4536
|
+
throw new Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name');
|
|
5572
4537
|
const target = await fs.stat(`/proc/${process.pid}/fd/${handle.fd}`);
|
|
5573
4538
|
if (target.dev !== info.dev || target.ino !== info.ino) throw new Error('managed-browser-socket-directory-changed');
|
|
5574
4539
|
return {endpoint, address, close:() => handle.close()};
|
|
@@ -6007,7 +4972,11 @@ if (playwrightConsent && interactivePlaywright && playwrightSkill && playwrightR
|
|
|
6007
4972
|
!playwrightConfig.env && !playwrightConfig.env_vars?.length) {
|
|
6008
4973
|
playwrightController = async launchArgs => {
|
|
6009
4974
|
try { return await managedPlaywright(launchArgs, undefined, refreshPlaywrightConsent); }
|
|
6010
|
-
catch {
|
|
4975
|
+
catch (error) {
|
|
4976
|
+
if (error?.message?.startsWith('UNIX_SOCKET_PATH_TOO_LONG'))
|
|
4977
|
+
process.stderr.write('gestalt: Unix socket pathname exceeds the platform byte limit; create a new v2 session or shorten the endpoint name.\n');
|
|
4978
|
+
if (error?.message?.startsWith('UNIX_SOCKET_PLATFORM_UNSUPPORTED'))
|
|
4979
|
+
process.stderr.write('gestalt: no verified Unix socket pathname capacity for this platform.\n');
|
|
6011
4980
|
playwrightNotice('managed-runtime-unavailable'); playwrightController = undefined;
|
|
6012
4981
|
return launch(['--no-daemon', ...launchArgs]);
|
|
6013
4982
|
}
|
|
@@ -6026,40 +4995,19 @@ if (common && serenaSkill && serenaSkill.enabled !== false && serenaRules.at(-1)
|
|
|
6026
4995
|
.every(name => install.tools.some(tool => tool.name === name && tool.inputSchema?.type === 'object')))
|
|
6027
4996
|
throw new Error('invalid-installation');
|
|
6028
4997
|
for (const executable of [install.executable, install.python, install.uv]) await access(executable, constants.X_OK);
|
|
6029
|
-
capabilities[
|
|
6030
|
-
capabilities[
|
|
4998
|
+
capabilities[0].valid = true;
|
|
4999
|
+
capabilities[0].config = managedToolApproval({ ...serenaReserved, ...capabilities[0].config,
|
|
6031
5000
|
cwd, env_vars: ['CODEX_HOME','GESTALT_HOME',...scratchNames],
|
|
6032
5001
|
enabled: true, required: true, startup_readiness: 'connection', startup_timeout_ms: budget });
|
|
6033
|
-
capabilities[
|
|
5002
|
+
capabilities[0].context = '<gestalt_serena_capability>\nSerena is connected to this workspace through a confined, policy-bearing native proxy. '
|
|
6034
5003
|
+ 'A listed catalog does not prove language readiness: first call get_symbols_overview on a current project source file '
|
|
6035
5004
|
+ 'and verify success before relying on semantics or editing. On failure use native code tools. '
|
|
6036
5005
|
+ 'Session and child permissions and approvals apply; plan mode prohibits edits. Do not switch projects or modes.\n'
|
|
6037
5006
|
+ guidance + '\n</gestalt_serena_capability>';
|
|
6038
5007
|
} catch (error) { diagnoseSerena(error.code === 'ENOENT' ? 'not-installed' : 'invalid-installation-or-plugin'); }
|
|
6039
5008
|
} else if (serenaConflict) diagnoseSerena('session-config-conflict');
|
|
6040
|
-
let ready = { status: 'absent' };
|
|
6041
|
-
if (state?.config?.skills?.include_instructions === false || state?.config?.features?.hooks !== true || conflict)
|
|
6042
|
-
ready = { status: 'unavailable', reason: 'session-config-conflict' };
|
|
6043
|
-
if (common && skill && !conflict) {
|
|
6044
|
-
try {
|
|
6045
|
-
const guidance = await usableGuidance(skill);
|
|
6046
|
-
ready = await readiness(remainingTime());
|
|
6047
|
-
if (ready.schemaVersion === 1 && ready.status === 'ready' && typeof ready.version === 'string' && /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(ready.version) &&
|
|
6048
|
-
/^http:\/\/(127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(ready.endpoint)) {
|
|
6049
|
-
capabilities[0].valid = true;
|
|
6050
|
-
capabilities[0].config = { command: manager, args: ['xerj', 'mcp', '--url', ready.endpoint], cwd,
|
|
6051
|
-
env_vars: ['CODEX_HOME','GESTALT_HOME','XERJ_API_KEY','XERJ_AUTH',...scratchNames], enabled: true, required: true,
|
|
6052
|
-
startup_readiness: 'connection', startup_timeout_ms: Math.max(1, remainingTime()),
|
|
6053
|
-
enabled_tools: ['xerj_search', 'xerj_map', 'xerj_code_search'], default_tools_approval_mode: 'approve' };
|
|
6054
|
-
capabilities[0].context = '<gestalt_xerj_capability>\ngestalt:xerj guidance from ' + skill.path
|
|
6055
|
-
+ '\nVerified retrieval tools are available for this session.\n' + guidance + '\n</gestalt_xerj_capability>';
|
|
6056
|
-
}
|
|
6057
|
-
} catch { ready = { status: 'unavailable', reason: 'incompatible-plugin-or-runtime' }; }
|
|
6058
|
-
}
|
|
6059
|
-
if (ready.status === 'unavailable') diagnose(ready.reason);
|
|
6060
5009
|
if (interrupted) process.exit(interruptionCode);
|
|
6061
|
-
|
|
6062
|
-
if (capabilities[1].valid) readinessDeadline = Math.max(readinessDeadline, Date.now() + budget);
|
|
5010
|
+
if (capabilities[0].valid) readinessDeadline = Math.max(readinessDeadline, Date.now() + budget);
|
|
6063
5011
|
const compose = () => {
|
|
6064
5012
|
hookCommands.clear();
|
|
6065
5013
|
expectedHookCount = 0;
|
|
@@ -6103,23 +5051,17 @@ async function selection() {
|
|
|
6103
5051
|
for (const cap of capabilities) cap.valid = false;
|
|
6104
5052
|
selected = compose();
|
|
6105
5053
|
}
|
|
6106
|
-
if (capabilities[0].valid) {
|
|
6107
|
-
const remaining = remainingTime();
|
|
6108
|
-
if (!remaining) { diagnose('readiness-deadline'); capabilities[0].valid = false; return selection(); }
|
|
6109
|
-
selected = selected.map(flag => flag.startsWith(`mcp_servers.${serverName}=`)
|
|
6110
|
-
? flag.replace(/"startup_timeout_ms"=\d+/, `"startup_timeout_ms"=${remaining}`) : flag);
|
|
6111
|
-
}
|
|
6112
5054
|
return selected;
|
|
6113
5055
|
}
|
|
6114
5056
|
let result = await launch(appendFlags(await selection()));
|
|
6115
5057
|
// Drop only the failed optional connection, preserving the independent service.
|
|
6116
|
-
//
|
|
5058
|
+
// Retry only the selected retained service after a connection failure.
|
|
6117
5059
|
for (let attempt = 0; result.code !== 0 && !interrupted && attempt < capabilities.length; attempt++) {
|
|
6118
5060
|
const failed = capabilities.filter(cap => cap.valid && result.startupFailed.has(cap.name));
|
|
6119
5061
|
if (!failed.length) break;
|
|
6120
5062
|
for (const cap of failed) {
|
|
6121
5063
|
cap.valid = false;
|
|
6122
|
-
|
|
5064
|
+
diagnoseSerena('runtime-connection-failed');
|
|
6123
5065
|
}
|
|
6124
5066
|
readinessDeadline = Date.now() + budget;
|
|
6125
5067
|
result = await launch(appendFlags(await selection()));
|
|
@@ -6158,7 +5100,7 @@ command_cli_owned() {
|
|
|
6158
5100
|
GESTALT_STARTUP_DIAGNOSTICS_DONE=1 PATH="$gestalt_home/bin:$codex_home/bin:$PATH" \
|
|
6159
5101
|
codex "${forwarded_args[@]}" ;;
|
|
6160
5102
|
esac
|
|
6161
|
-
|
|
5103
|
+
launch_cli_with_capabilities "${forwarded_args[@]}"
|
|
6162
5104
|
}
|
|
6163
5105
|
|
|
6164
5106
|
|
|
@@ -6282,6 +5224,13 @@ command_mobile() {
|
|
|
6282
5224
|
local mobile_workspace=$PWD mobile_arg_index
|
|
6283
5225
|
|
|
6284
5226
|
strip_separator "$@"
|
|
5227
|
+
# Reject obsolete manually supplied options before installation or startup.
|
|
5228
|
+
# Stored descriptors are adapted separately by the explicit restart worker.
|
|
5229
|
+
for ((mobile_arg_index = 0; mobile_arg_index < ${#forwarded_args[@]}; mobile_arg_index++)); do
|
|
5230
|
+
case ${forwarded_args[mobile_arg_index]} in
|
|
5231
|
+
--xerj | --xerj=*) die 'Xerj has been retired; omit --xerj when starting Mobile. Run gestalt update before restarting older generated launchers.' ;;
|
|
5232
|
+
esac
|
|
5233
|
+
done
|
|
6285
5234
|
if [[ ! -x $mobile_bin ]]; then
|
|
6286
5235
|
log 'Gestalt Mobile is not installed; installing it now'
|
|
6287
5236
|
install_mobile
|
|
@@ -6334,7 +5283,6 @@ command_mobile() {
|
|
|
6334
5283
|
GESTALT_AGENTS_VERSION="$gestalt_agents_version" \
|
|
6335
5284
|
GESTALT_AGENTS_PLUGIN_ROOT="$gestalt_plugin_root" \
|
|
6336
5285
|
GESTALT_CONTEXT_MODE_VERSION="$context_mode_version" \
|
|
6337
|
-
GESTALT_XERJ_VERSION="$(installed_xerj_version)" \
|
|
6338
5286
|
GESTALT_SERENA_VERSION="$(serena_versions serena 2>/dev/null || true)" \
|
|
6339
5287
|
GESTALT_UV_VERSION="$(serena_versions uv 2>/dev/null || true)" \
|
|
6340
5288
|
GESTALT_SERENA_PYTHON_VERSION="$(serena_versions python 2>/dev/null || true)" \
|
|
@@ -6354,14 +5302,6 @@ print_check() {
|
|
|
6354
5302
|
printf '%-24s %s\n' "$label" "$status"
|
|
6355
5303
|
}
|
|
6356
5304
|
|
|
6357
|
-
installed_xerj_version() {
|
|
6358
|
-
local output
|
|
6359
|
-
output=$(bash "${BASH_SOURCE[0]}" xerj -V 2>/dev/null) || return 0
|
|
6360
|
-
if [[ $output =~ ^xerj[[:space:]]+([A-Za-z0-9][A-Za-z0-9.+_-]{0,99})$ ]]; then
|
|
6361
|
-
printf '%s' "${BASH_REMATCH[1]}"
|
|
6362
|
-
fi
|
|
6363
|
-
}
|
|
6364
|
-
|
|
6365
5305
|
command_version() {
|
|
6366
5306
|
local value plugin
|
|
6367
5307
|
printf 'gestalt %s\n' "$GESTALT_CLI_VERSION"
|
|
@@ -6379,8 +5319,6 @@ command_version() {
|
|
|
6379
5319
|
if command -v kimi >/dev/null 2>&1; then
|
|
6380
5320
|
value=$(kimi --version 2>/dev/null) && print_check 'Kimi CLI' "$value"
|
|
6381
5321
|
fi
|
|
6382
|
-
value=$(installed_xerj_version)
|
|
6383
|
-
if [[ -n $value ]]; then print_check 'xerj' "$value"; fi
|
|
6384
5322
|
value=$(serena_versions serena 2>/dev/null || true)
|
|
6385
5323
|
print_check 'Serena' "${value:-NOT INSTALLED (optional)}"
|
|
6386
5324
|
value=$(command_playwright version 2>/dev/null || true)
|
|
@@ -6394,34 +5332,6 @@ command_version() {
|
|
|
6394
5332
|
return 0
|
|
6395
5333
|
}
|
|
6396
5334
|
|
|
6397
|
-
check_xerj() {
|
|
6398
|
-
local version report
|
|
6399
|
-
version=$(installed_xerj_version)
|
|
6400
|
-
print_check 'xerj' "${version:-NOT AVAILABLE (optional retrieval)}"
|
|
6401
|
-
if [[ -n $version ]]; then
|
|
6402
|
-
if command -v flock >/dev/null 2>&1 && command -v setpriv >/dev/null 2>&1; then
|
|
6403
|
-
print_check 'xerj auto-index' 'available (flock and setpriv)'
|
|
6404
|
-
else
|
|
6405
|
-
print_check 'xerj auto-index' 'unavailable: install util-linux flock/setpriv, or use --xerj manual'
|
|
6406
|
-
fi
|
|
6407
|
-
fi
|
|
6408
|
-
if command -v node >/dev/null 2>&1; then
|
|
6409
|
-
report=$(bash "${BASH_SOURCE[0]}" xerj probe 2>/dev/null) || report='{}'
|
|
6410
|
-
# shellcheck disable=SC2016 # JavaScript owns this interpolation.
|
|
6411
|
-
printf '%s' "$report" | node -e '
|
|
6412
|
-
let input = "";
|
|
6413
|
-
process.stdin.on("data", chunk => { input += chunk; });
|
|
6414
|
-
process.stdin.on("end", () => {
|
|
6415
|
-
let result;
|
|
6416
|
-
try { result = JSON.parse(input); } catch { result = {}; }
|
|
6417
|
-
const reason = /^[a-z-]{1,80}$/.test(result.reason ?? "") ? result.reason : "probe-failed";
|
|
6418
|
-
console.log("xerj readiness".padEnd(24) + " " +
|
|
6419
|
-
(result.status === "ready" ? "ready" : `unavailable (${reason}; direct source search remains available)`));
|
|
6420
|
-
});
|
|
6421
|
-
'
|
|
6422
|
-
fi
|
|
6423
|
-
}
|
|
6424
|
-
|
|
6425
5335
|
read_plugin_version() {
|
|
6426
5336
|
local -r plugin_name=$1
|
|
6427
5337
|
# shellcheck disable=SC2016 # The Node program intentionally owns its JavaScript interpolation.
|
|
@@ -6782,17 +5692,6 @@ run_startup_diagnostics() {
|
|
|
6782
5692
|
fi
|
|
6783
5693
|
}
|
|
6784
5694
|
|
|
6785
|
-
check_xerj_watch_layout() {
|
|
6786
|
-
case $1 in s3://* | r2://*) return 0 ;; esac
|
|
6787
|
-
local source state
|
|
6788
|
-
source=$(CDPATH='' cd -- "$1" && pwd -P) || return 1
|
|
6789
|
-
state=$(canonical_xerj_root "$2") || return 1
|
|
6790
|
-
if [[ $source == / || $state == "$source" || $state == "$source/"* ]]; then
|
|
6791
|
-
printf '%s\n' 'gestalt: XERJ watcher state is inside the watched root. Start Mobile with --cwd pointing to a narrower source folder, or set GESTALT_XERJ_AUTO_INDEX_HOME to a persistent absolute directory outside that root before starting Mobile. Restarting or reinstalling components does not repair this layout.' >&2
|
|
6792
|
-
return 1
|
|
6793
|
-
fi
|
|
6794
|
-
}
|
|
6795
|
-
|
|
6796
5695
|
run_codex_doctor() {
|
|
6797
5696
|
# Session scratch forwarding is required for session launches, but is optional
|
|
6798
5697
|
# for an operator's read-only diagnostics. Do not invent an owner or edit config.
|
|
@@ -6922,15 +5821,6 @@ command_doctor() {
|
|
|
6922
5821
|
fi
|
|
6923
5822
|
|
|
6924
5823
|
check_supervision_capability_coherence || failed=true
|
|
6925
|
-
check_xerj
|
|
6926
|
-
if [[ -x $gestalt_home/xerj/xerj ]]; then
|
|
6927
|
-
if check_xerj_watch_layout "$workspace" "${GESTALT_XERJ_AUTO_INDEX_HOME:-$codex_home/xerj-data/autoindex}"; then
|
|
6928
|
-
print_check 'XERJ watch layout' 'ready'
|
|
6929
|
-
else
|
|
6930
|
-
print_check 'XERJ watch layout' 'INVALID (watcher journals must be outside --cwd)'
|
|
6931
|
-
failed=true
|
|
6932
|
-
fi
|
|
6933
|
-
fi
|
|
6934
5824
|
run_doctor_command 'Optional skill collection' command_skills status || failed=true
|
|
6935
5825
|
|
|
6936
5826
|
if command -v codex >/dev/null 2>&1; then
|
|
@@ -6996,6 +5886,9 @@ main() {
|
|
|
6996
5886
|
'gestalt scratch inspect-tool-leases --cwd ROOT --owner ID' \
|
|
6997
5887
|
'gestalt scratch recover-tool-leases --cwd ROOT --owner ID --expect TOKEN --confirm-quiescent' \
|
|
6998
5888
|
'Use the token from inspect-tool-leases to release abandoned Mobile Serena/Playwright borrowers.' \
|
|
5889
|
+
'gestalt scratch inspect-publication --cwd ROOT' \
|
|
5890
|
+
'gestalt scratch recover-publication --cwd ROOT --expect TOKEN --confirm-quiescent' \
|
|
5891
|
+
'Use the token from inspect-publication to clear an abandoned empty workspace publication fence.' \
|
|
6999
5892
|
'Never use these overrides on a live session. Payload and provider history are retained.'
|
|
7000
5893
|
else
|
|
7001
5894
|
require_command node
|
|
@@ -7004,7 +5897,7 @@ main() {
|
|
|
7004
5897
|
;;
|
|
7005
5898
|
cli) command_cli "$@" ;;
|
|
7006
5899
|
mobile) command_mobile "$@" ;;
|
|
7007
|
-
xerj)
|
|
5900
|
+
xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
|
|
7008
5901
|
serena) command_serena "$@" ;;
|
|
7009
5902
|
playwright) command_playwright "$@" ;;
|
|
7010
5903
|
path) command_path "$@" ;;
|