@jaromil/gestalt 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  set -Eeuo pipefail
4
4
  IFS=$'\n\t'
5
5
 
6
- readonly GESTALT_CLI_VERSION='0.16.0'
6
+ readonly GESTALT_CLI_VERSION='0.17.0'
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'
@@ -119,10 +119,92 @@ function scratchJson(file) {
119
119
  return JSON.parse(scratchFs.readFileSync(fd, 'utf8'));
120
120
  } finally { scratchFs.closeSync(fd); }
121
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
+ }
122
204
  function scratchContext(environment = process.env, allowReleased = false) {
123
205
  if (!Object.hasOwn(environment, scratchVariable)) return null;
124
206
  const context = JSON.parse(environment[scratchVariable]);
125
- scratchAssert(context?.schemaVersion === 1 && scratchId(context.ownerId));
207
+ scratchAssert([1,2].includes(context?.schemaVersion) && scratchId(context.ownerId));
126
208
  scratchCanonical(context.workspacePath);
127
209
  const container = scratchPath.join(context.workspacePath, 'tmp', 'sessions');
128
210
  scratchAssert(context.directory === scratchPath.join(container, context.ownerId) &&
@@ -135,11 +217,15 @@ function scratchContext(environment = process.env, allowReleased = false) {
135
217
  scratchAssert(!process.getuid || scratchFs.lstatSync(parent).uid === process.getuid());
136
218
  for (const directory of [container, context.directory]) scratchPrivate(directory);
137
219
  const marker = scratchJson(context.markerPath);
138
- scratchAssert(marker?.schemaVersion === 1 && marker.ownerId === context.ownerId &&
220
+ scratchAssert(marker?.schemaVersion === context.schemaVersion && marker.ownerId === context.ownerId &&
139
221
  marker.workspacePath === context.workspacePath && scratchId(marker.sessionId) &&
140
222
  typeof marker.createdAt === 'string' && Number.isFinite(Date.parse(marker.createdAt)) &&
141
223
  Array.isArray(marker.providerThreads) && marker.providerThreads.every(thread =>
142
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);
143
229
  if (marker.ownerKind === 'mobile-session') {
144
230
  scratchAssert(context.ownerId === 'mobile-' + scratchCrypto.createHash('sha256').update(marker.sessionId).digest('hex') &&
145
231
  marker.authority?.kind === 'mobile-roster' && marker.authority.sessionId === marker.sessionId);
@@ -160,7 +246,8 @@ function scratchContext(environment = process.env, allowReleased = false) {
160
246
  }
161
247
  function scratchEnvironment(environment = process.env) {
162
248
  const context = scratchContext(environment);
163
- return context ? { ...environment, TMPDIR: context.directory, TMP: context.directory, TEMP: context.directory } : { ...environment };
249
+ const directory=context && scratchTemporaryDirectory(context);
250
+ return context ? { ...environment, TMPDIR: directory, TMP: directory, TEMP: directory } : { ...environment };
164
251
  }
165
252
  function scratchDiscoveryEnvironment(environment = process.env) {
166
253
  const result = { ...environment };
@@ -189,7 +276,10 @@ function scratchContainer(workspace) {
189
276
  }
190
277
  function scratchOwnerContext(workspace, ownerId) {
191
278
  const directory = scratchPath.join(workspace, 'tmp', 'sessions', ownerId);
192
- return {schemaVersion: 1, workspacePath: workspace, ownerId, directory, markerPath: scratchPath.join(directory, '.gestalt-owner.json')};
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;
193
283
  }
194
284
  function scratchLeaseRecords(context) {
195
285
  const directory = scratchPath.join(context.directory, 'leases');
@@ -225,20 +315,34 @@ function scratchAncestorOwner(context) {
225
315
  return {
226
316
  context, identity: scratchDirectoryIdentity(context.directory),
227
317
  provenance: JSON.stringify([marker.schemaVersion, marker.ownerKind, marker.ownerId, marker.workspacePath,
228
- 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]),
229
319
  };
230
320
  }
231
- function scratchManagedAncestors(workspace) {
321
+ function scratchManagedAncestors(workspace, ancestors=[], visiting=new Set()) {
322
+ scratchAssert(!visiting.has(workspace) && visiting.size<64);
323
+ visiting.add(workspace);
232
324
  const parts = workspace.slice(scratchPath.parse(workspace).root.length).split(scratchPath.sep).filter(Boolean);
233
- const ancestors = [];
325
+ const runtimeBase=process.getuid?scratchRuntimeContainer():undefined;
234
326
  let directory = scratchPath.parse(workspace).root;
235
327
  for (let i = 0; i < parts.length; i++) {
236
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
+ }
237
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);
238
341
  const ownerWorkspace = scratchPath.dirname(scratchPath.dirname(scratchPath.dirname(directory)));
239
342
  ancestors.push(scratchAncestorOwner(scratchOwnerContext(ownerWorkspace, parts[i])));
240
343
  }
241
344
  }
345
+ visiting.delete(workspace);
242
346
  return ancestors;
243
347
  }
244
348
  function scratchRevalidateAncestor(ancestor) {
@@ -333,9 +437,38 @@ function scratchRecoverToolLeases(workspace, ownerId, token) {
333
437
  {...lease, state: 'released', consumers: [], updatedAt: new Date().toISOString()});
334
438
  }
335
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
+ }
336
469
  function scratchRecoveryCommand(args) {
337
470
  const [action, ...options] = args;
338
- 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));
339
472
  const values = {};
340
473
  let confirmed = false;
341
474
  for (let index = 0; index < options.length; index++) {
@@ -345,7 +478,18 @@ function scratchRecoveryCommand(args) {
345
478
  scratchAssert(typeof options[index + 1] === 'string' && !options[index + 1].startsWith('--'));
346
479
  values[name] = options[++index];
347
480
  }
348
- 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
+ }
349
493
  if (action === 'inspect' || action === 'inspect-tool-leases') {
350
494
  scratchAssert(!confirmed && !values['--expect']);
351
495
  const snapshot = action === 'inspect' ? scratchContainmentSnapshot(values['--cwd'], values['--owner'])
@@ -360,6 +504,7 @@ function scratchRecoveryCommand(args) {
360
504
  }
361
505
  }
362
506
  function scratchWithContainment(workspace, publish) {
507
+ return scratchWorkspacePublication(workspace,()=>{
363
508
  scratchCanonical(workspace);
364
509
  const selected = scratchDirectoryIdentity(workspace), ancestors = scratchManagedAncestors(workspace), claims = [];
365
510
  try {
@@ -402,6 +547,7 @@ function scratchWithContainment(workspace, publish) {
402
547
  }
403
548
  if (failure) throw failure;
404
549
  }
550
+ });
405
551
  }
406
552
  function scratchAllocate(workspace,kind,consumer) {
407
553
  scratchAssert(['cli-session','workspace-service'].includes(kind)&&scratchId(consumer));
@@ -414,6 +560,10 @@ function scratchAllocate(workspace,kind,consumer) {
414
560
  const leaseId=scratchCrypto.randomUUID(),time=new Date().toISOString();
415
561
  const lease={schemaVersion:1,ownerId,workspacePath:workspace,leaseId,state:'active',processIdentity:scratchCrypto.randomUUID(),createdAt:time,updatedAt:time,consumers:[consumer]};
416
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
+ }
417
567
  scratchPublish(scratchPath.join(context.directory,'leases',leaseId+'.json'),lease,true);scratchPublish(context.markerPath,marker,true);
418
568
  scratchContext({[scratchVariable]:JSON.stringify(context)});return {context,lease,lock};
419
569
  });
@@ -437,6 +587,7 @@ function scratchRelease(ownership) {
437
587
  });
438
588
  }
439
589
  function scratchMetadata(context, operation, waitMs = 0) {
590
+ return scratchWorkspacePublication(context.workspacePath,()=>{
440
591
  scratchContext({[scratchVariable]: JSON.stringify(context)});
441
592
  const mobile = scratchJson(context.markerPath).ownerKind === 'mobile-session';
442
593
  // Mobile cleanup/association use this same controller fence. CLI/service
@@ -457,6 +608,7 @@ function scratchMetadata(context, operation, waitMs = 0) {
457
608
  if (mobile) scratchAssert(!scratchFs.existsSync(scratchPath.join(context.directory, '.association-lock')));
458
609
  return operation();
459
610
  } finally {scratchFs.rmdirSync(lock);}
611
+ });
460
612
  }
461
613
  function scratchBorrow(context, consumer) {
462
614
  scratchAssert(scratchId(consumer));
@@ -633,7 +785,7 @@ async function scratchCli(manager, args) {
633
785
  }
634
786
  // END SESSION SCRATCH RUNTIME
635
787
  if (process.argv[1] === 'validate') {
636
- try {const context = scratchContext(); process.stdout.write(scratchJson(context.markerPath).ownerKind + '\n' + context.directory);}
788
+ try {const context = scratchContext(); process.stdout.write(scratchJson(context.markerPath).ownerKind + '\n' + scratchTemporaryDirectory(context));}
637
789
  catch { process.stderr.write('gestalt: invalid managed session temporary context\n'); process.exitCode = 1; }
638
790
  }
639
791
  if (process.argv[1] === 'scratch') {
@@ -3394,37 +3546,122 @@ renameSync(temporary, destination);
3394
3546
  NODE
3395
3547
  }
3396
3548
 
3549
+ agents_setup_uses_node() {
3550
+ [[ -f $marketplace_setup && -f ${marketplace_setup%.sh}.mjs && -f ${marketplace_setup%/*}/scripts/setup-agents.mjs ]]
3551
+ }
3552
+
3553
+ prepare_agents_homes() {
3554
+ local native_owner=false
3555
+ if agents_setup_uses_node; then native_owner=true; fi
3556
+ node - "$codex_home" "$gestalt_home" "$native_owner" <<'NODE'
3557
+ const { accessSync, constants, mkdirSync, realpathSync, statSync } = require('node:fs');
3558
+ const { basename, dirname, isAbsolute, join, relative, sep } = require('node:path');
3559
+ function canonical(path) {
3560
+ try { return realpathSync(path); }
3561
+ catch (error) {
3562
+ if (error.code !== 'ENOENT' || dirname(path) === path) throw error;
3563
+ return join(canonical(dirname(path)), basename(path));
3564
+ }
3565
+ }
3566
+ function read(path) {
3567
+ try { return statSync(path); }
3568
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
3569
+ }
3570
+ try {
3571
+ const [selectedCodex, selectedGestalt, nativeOwner] = process.argv.slice(2);
3572
+ const [codex, gestalt] = [selectedCodex, selectedGestalt].map(canonical);
3573
+ const within = (root, path) => {
3574
+ const rest = relative(root, path);
3575
+ return !isAbsolute(rest) && rest !== '..' && !rest.startsWith('..' + sep);
3576
+ };
3577
+ const home = realpathSync(process.env.HOME);
3578
+ if (within(codex, gestalt) || within(gestalt, codex) || [codex, gestalt].some(path => within(path, home)))
3579
+ throw new Error('CODEX_HOME and GESTALT_HOME must be separate managed directories outside HOME itself');
3580
+ const missing = [];
3581
+ for (const path of [codex, gestalt]) {
3582
+ const info = read(path);
3583
+ if (!info) { missing.push(path); continue; }
3584
+ try {
3585
+ if (!info.isDirectory()) throw new Error('expected a directory');
3586
+ accessSync(path, constants.W_OK | constants.X_OK);
3587
+ } catch { throw new Error('managed directory is not writable: ' + path); }
3588
+ if (nativeOwner === 'true' && (info.uid !== process.getuid() || (info.mode & 0o077) !== 0))
3589
+ throw new Error('native Agents setup requires a directory private to its owner: ' + path + '; select private managed homes before retrying');
3590
+ }
3591
+ for (const path of missing) mkdirSync(path, { recursive: true, mode: 0o700 });
3592
+ } catch (error) { console.error('gestalt: ' + error.message); process.exitCode = 1; }
3593
+ NODE
3594
+ }
3595
+
3397
3596
  run_marketplace_setup() {
3398
3597
  local -r mode=$1
3399
3598
  local -r include_extra_skills=$2
3400
3599
  local marketplace_action
3401
- agents_setup_stage=''
3402
- local -a setup_args=()
3600
+ # Bash can unwind this function before running the shell's EXIT trap.
3601
+ agents_setup_stage='' agents_setup_handoff=false agents_setup_snapshot_ready=false
3602
+ agents_codex_gate=false agents_gestalt_gate=false
3603
+ agents_operation_lock=$codex_home/.gestalt-manager-setup.lock
3604
+ agents_codex_gate_path=$codex_home/.gestalt-setup.lock
3605
+ agents_gestalt_gate_path=$gestalt_home/.gestalt-setup.lock
3403
3606
 
3404
3607
  check_node_version
3405
3608
  require_command npm
3406
3609
  require_command codex
3407
- mkdir -p -- "$codex_home" "$gestalt_home"
3408
- agents_setup_lock=$codex_home/.gestalt-setup.lock
3409
- mkdir -- "$agents_setup_lock" 2>/dev/null ||
3410
- die 'Agents setup is already running or Codex home is not writable; verify the previous installer exited before removing .gestalt-setup.lock'
3411
- # Serialize setup and roll back manager-owned config edits on failure. Package
3412
- # installation and its own profile transaction remain the delegated owner's job.
3610
+ prepare_agents_homes
3611
+ mkdir -m 700 -- "$agents_operation_lock" 2>/dev/null ||
3612
+ die "Agents setup is already running or ownership is unknown: $agents_operation_lock"
3613
+ setup_acquire_gates() {
3614
+ if ! "$agents_codex_gate"; then
3615
+ mkdir -m 700 -- "$agents_codex_gate_path" 2>/dev/null || return 1
3616
+ agents_codex_gate=true
3617
+ fi
3618
+ if ! "$agents_gestalt_gate"; then
3619
+ mkdir -m 700 -- "$agents_gestalt_gate_path" 2>/dev/null || return 1
3620
+ agents_gestalt_gate=true
3621
+ fi
3622
+ }
3623
+ setup_release_gates() {
3624
+ local status=0
3625
+ if "$agents_gestalt_gate"; then
3626
+ if rmdir -- "$agents_gestalt_gate_path"; then agents_gestalt_gate=false; else status=1; fi
3627
+ fi
3628
+ if "$agents_codex_gate"; then
3629
+ if rmdir -- "$agents_codex_gate_path"; then agents_codex_gate=false; else status=1; fi
3630
+ fi
3631
+ return "$status"
3632
+ }
3633
+ # Keep the Manager operation lock while the Node delegate owns its setup
3634
+ # gates. Only restore a delegated snapshot with both gates and known bytes.
3413
3635
  setup_cleanup() {
3414
3636
  local status=$?
3637
+ local retain=false
3415
3638
  trap - EXIT HUP INT TERM ERR
3416
- # Cleanup must not replace the triggering status or prevent the manager's
3417
- # preexisting EXIT cleanup (including the update/restart worker lock).
3639
+ # Successful setup restores the regular EXIT trap before returning. Bash
3640
+ # can enter this trap with status 0 even when setup did not finish.
3418
3641
  set +e
3419
- if (( status != 0 )) && [[ -n $agents_setup_stage ]]; then
3420
- if [[ -f $agents_setup_stage/config.toml ]]; then
3421
- mv -f -- "$agents_setup_stage/config.toml" "$codex_home/config.toml"
3642
+ if (( status == 0 )); then
3643
+ status=1
3644
+ log 'error: Agents setup exited before completing'
3645
+ fi
3646
+ if "$agents_setup_snapshot_ready" && [[ -n $agents_setup_stage ]]; then
3647
+ if ! setup_acquire_gates; then
3648
+ retain=true
3649
+ elif "$agents_setup_handoff" && { [[ -L $codex_home/config.toml ]] ||
3650
+ ! cmp -s -- "$agents_setup_stage/config-delegated" "$codex_home/config.toml"; }; then
3651
+ retain=true
3652
+ elif [[ -f $agents_setup_stage/config.toml ]]; then
3653
+ mv -f -- "$agents_setup_stage/config.toml" "$codex_home/config.toml" || retain=true
3422
3654
  elif [[ -f $agents_setup_stage/config-absent ]]; then
3423
- rm -f -- "$codex_home/config.toml"
3655
+ rm -f -- "$codex_home/config.toml" || retain=true
3424
3656
  fi
3425
3657
  fi
3426
- [[ -z $agents_setup_stage ]] || rm -rf -- "$agents_setup_stage"
3427
- rmdir -- "$agents_setup_lock" 2>/dev/null || true
3658
+ setup_release_gates || retain=true
3659
+ if "$retain"; then
3660
+ log "Agents setup ownership or rollback is unconfirmed; preserved lock $agents_operation_lock and snapshot ${agents_setup_stage:-unavailable}"
3661
+ else
3662
+ [[ -z $agents_setup_stage ]] || rm -rf -- "$agents_setup_stage"
3663
+ rmdir -- "$agents_operation_lock" 2>/dev/null || true
3664
+ fi
3428
3665
  cleanup
3429
3666
  exit "$status"
3430
3667
  }
@@ -3432,6 +3669,7 @@ run_marketplace_setup() {
3432
3669
  trap 'exit 129' HUP
3433
3670
  trap 'exit 130' INT
3434
3671
  trap 'exit 143' TERM
3672
+ setup_acquire_gates || die 'Agents setup is already running or its setup lock ownership is unknown'
3435
3673
  [[ ! -L $codex_home/config.toml &&
3436
3674
  (! -e $codex_home/config.toml || -f $codex_home/config.toml) ]] ||
3437
3675
  die 'Codex config must be a regular file for setup'
@@ -3441,11 +3679,7 @@ run_marketplace_setup() {
3441
3679
  else
3442
3680
  touch "$agents_setup_stage/config-absent"
3443
3681
  fi
3444
- configure_codex_permissions
3445
- # Establish app defaults before the owner appends its managed MCP section,
3446
- # keeping first-install ordering identical to later reconciliation.
3447
- configure_codex_tool_approvals
3448
-
3682
+ agents_setup_snapshot_ready=true
3449
3683
  marketplace_action=upgrade
3450
3684
  if [[ $mode == install && ! -f $marketplace_setup ]]; then
3451
3685
  marketplace_action=add
@@ -3467,13 +3701,28 @@ run_marketplace_setup() {
3467
3701
  [[ -f $marketplace_setup ]] ||
3468
3702
  die "marketplace setup script is missing after ${marketplace_action}: $marketplace_setup"
3469
3703
 
3470
- if [[ $include_extra_skills == true ]]; then
3471
- setup_args+=(--extra-skills)
3472
- fi
3704
+ # Refresh can replace the legacy owner. Check the selected owner before
3705
+ # editing the profile, while the original snapshot is still available.
3706
+ if agents_setup_uses_node; then prepare_agents_homes; fi
3707
+ configure_codex_permissions
3708
+ # Establish app defaults before the owner appends its managed MCP section.
3709
+ configure_codex_tool_approvals
3473
3710
 
3474
3711
  log 'preparing context mode, plugins, and agent profiles'
3475
- CODEX_HOME=$codex_home GESTALT_HOME=$gestalt_home \
3476
- bash "$marketplace_setup" "${setup_args[@]}"
3712
+ if agents_setup_uses_node; then
3713
+ cp -p -- "$codex_home/config.toml" "$agents_setup_stage/config-delegated"
3714
+ agents_setup_handoff=true
3715
+ setup_release_gates
3716
+ fi
3717
+ # Bash 3.2 with nounset rejects expanding an empty array.
3718
+ if [[ $include_extra_skills == true ]]; then
3719
+ CODEX_HOME=$codex_home GESTALT_HOME=$gestalt_home bash "$marketplace_setup" --extra-skills
3720
+ else
3721
+ CODEX_HOME=$codex_home GESTALT_HOME=$gestalt_home bash "$marketplace_setup"
3722
+ fi
3723
+ setup_acquire_gates || die 'Agents setup lock ownership is unknown after delegation'
3724
+ # Across the portable handoff another setup may have completed. If later
3725
+ # work fails, retain a changed configuration and the original snapshot.
3477
3726
  verify_context_mode_installation
3478
3727
  configure_codex_tool_approvals
3479
3728
  # Normalize our block after delegated sections/defaults are reconciled so the
@@ -3482,7 +3731,8 @@ run_marketplace_setup() {
3482
3731
  record_setup_provenance
3483
3732
  rm -rf -- "$agents_setup_stage"
3484
3733
  agents_setup_stage=''
3485
- rmdir -- "$agents_setup_lock"
3734
+ setup_release_gates
3735
+ rmdir -- "$agents_operation_lock"
3486
3736
  trap cleanup EXIT
3487
3737
  trap - HUP INT TERM
3488
3738
  }
@@ -3621,6 +3871,7 @@ NODE
3621
3871
 
3622
3872
  command_install() {
3623
3873
  parse_setup_options "$@"
3874
+ prepare_agents_homes
3624
3875
  command_skills install
3625
3876
  run_marketplace_setup install "$include_extra_skills"
3626
3877
  install_mobile
@@ -3632,6 +3883,7 @@ command_update() {
3632
3883
  case $update_component in
3633
3884
  all | gestalt)
3634
3885
  update_manager
3886
+ prepare_agents_homes
3635
3887
  retire_managed_xerj
3636
3888
  command_skills update
3637
3889
  run_marketplace_setup upgrade "$include_extra_skills"
@@ -3792,7 +4044,7 @@ command_update_restart_worker() {
3792
4044
  local -r restart_log=${4:-}
3793
4045
  local -r restart_lock=${5:-}
3794
4046
  local -r worker_component=${6:-all}
3795
- local restart_cwd restart_field manager_target
4047
+ local restart_cwd restart_field restart_index manager_target
3796
4048
  local -a restart_record restart_args migrated_restart_args update_args=()
3797
4049
 
3798
4050
  [[ -n $restart_log ]] || die 'the update-restart worker log path is missing'
@@ -3811,11 +4063,18 @@ command_update_restart_worker() {
3811
4063
  while IFS= read -r -d '' restart_field; do
3812
4064
  restart_record+=("$restart_field")
3813
4065
  done < "$restart_state"
3814
- ((${#restart_record[@]} >= 1)) || die 'the Gestalt Mobile restart descriptor is empty'
4066
+ [[ ${restart_record[0]+present} ]] || die 'the Gestalt Mobile restart descriptor is empty'
3815
4067
  restart_cwd=${restart_record[0]}
3816
- restart_args=("${restart_record[@]:1}")
3817
- retire_mobile_restart_arguments "${restart_args[@]}"
3818
- restart_args=("${migrated_restart_args[@]}")
4068
+ # Bash 3.2 can join a quoted array slice into one argument. Copy each field
4069
+ # explicitly, preserving empty fields and literal separators from the record.
4070
+ restart_args=()
4071
+ for ((restart_index = 1; restart_index < ${#restart_record[@]}; restart_index += 1)); do
4072
+ restart_args+=("${restart_record[restart_index]}")
4073
+ done
4074
+ # Empty arrays are unset under Bash 3.2 nounset; conditional expansion emits
4075
+ # zero arguments for them and retains each argument of a nonempty array.
4076
+ retire_mobile_restart_arguments ${restart_args[@]+"${restart_args[@]}"}
4077
+ restart_args=(${migrated_restart_args[@]+"${migrated_restart_args[@]}"})
3819
4078
  [[ $restart_cwd == /* && -d $restart_cwd ]] ||
3820
4079
  die "the Gestalt Mobile restart directory is invalid: $restart_cwd"
3821
4080
  [[ $worker_extra_skills == false || $worker_extra_skills == true ]] ||
@@ -3824,7 +4083,7 @@ command_update_restart_worker() {
3824
4083
  update_args+=(--extra-skills)
3825
4084
  fi
3826
4085
 
3827
- command_update "$worker_component" "${update_args[@]}"
4086
+ command_update "$worker_component" ${update_args[@]+"${update_args[@]}"}
3828
4087
  validate_mobile_restart_context "$relay_pid" "$restart_state"
3829
4088
  log "update succeeded; gracefully stopping Gestalt Mobile process $relay_pid"
3830
4089
  kill -TERM "$relay_pid"
@@ -3843,7 +4102,7 @@ command_update_restart_worker() {
3843
4102
  resolve_manager_target
3844
4103
  cd -- "$restart_cwd"
3845
4104
  log 'restarting Gestalt Mobile with its previous options'
3846
- exec "$manager_target" mobile -- "${restart_args[@]}"
4105
+ exec "$manager_target" mobile -- ${restart_args[@]+"${restart_args[@]}"}
3847
4106
  }
3848
4107
 
3849
4108
  strip_separator() {
@@ -4365,8 +4624,12 @@ async function managedPlaywright(launchArgs, reportDiagnostic = () => {}, checkC
4365
4624
  const {constants} = await import('node:fs');
4366
4625
  const {join} = await import('node:path');
4367
4626
  const endpoint = join(directory, 'frontend.sock');
4368
- if (Buffer.byteLength(endpoint) < 100 || process.platform !== 'linux')
4627
+ const capacity = ({linux:108,darwin:104})[process.platform];
4628
+ if (!capacity) throw new Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
4629
+ if (Buffer.byteLength(endpoint) + 1 <= capacity)
4369
4630
  return {endpoint, address:endpoint, close:async () => {}};
4631
+ if (process.platform !== 'linux')
4632
+ throw new Error('UNIX_SOCKET_PATH_TOO_LONG: use a bounded managed runtime root or shorten the endpoint name');
4370
4633
  const handle = await fs.open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
4371
4634
  try {
4372
4635
  const info = await handle.stat();
@@ -4376,6 +4639,8 @@ async function managedPlaywright(launchArgs, reportDiagnostic = () => {}, checkC
4376
4639
  // Keep the actual socket in its private owner. Linux resolves this short
4377
4640
  // descriptor address to that same directory for bind and native connect.
4378
4641
  const address = `/proc/${process.pid}/fd/${handle.fd}/frontend.sock`;
4642
+ if (Buffer.byteLength(address) + 1 > capacity)
4643
+ throw new Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name');
4379
4644
  const target = await fs.stat(`/proc/${process.pid}/fd/${handle.fd}`);
4380
4645
  if (target.dev !== info.dev || target.ino !== info.ino) throw new Error('managed-browser-socket-directory-changed');
4381
4646
  return {endpoint, address, close:() => handle.close()};
@@ -4814,7 +5079,11 @@ if (playwrightConsent && interactivePlaywright && playwrightSkill && playwrightR
4814
5079
  !playwrightConfig.env && !playwrightConfig.env_vars?.length) {
4815
5080
  playwrightController = async launchArgs => {
4816
5081
  try { return await managedPlaywright(launchArgs, undefined, refreshPlaywrightConsent); }
4817
- catch {
5082
+ catch (error) {
5083
+ if (error?.message?.startsWith('UNIX_SOCKET_PATH_TOO_LONG'))
5084
+ process.stderr.write('gestalt: Unix socket pathname exceeds the platform byte limit; create a new v2 session or shorten the endpoint name.\n');
5085
+ if (error?.message?.startsWith('UNIX_SOCKET_PLATFORM_UNSUPPORTED'))
5086
+ process.stderr.write('gestalt: no verified Unix socket pathname capacity for this platform.\n');
4818
5087
  playwrightNotice('managed-runtime-unavailable'); playwrightController = undefined;
4819
5088
  return launch(['--no-daemon', ...launchArgs]);
4820
5089
  }
@@ -5724,6 +5993,9 @@ main() {
5724
5993
  'gestalt scratch inspect-tool-leases --cwd ROOT --owner ID' \
5725
5994
  'gestalt scratch recover-tool-leases --cwd ROOT --owner ID --expect TOKEN --confirm-quiescent' \
5726
5995
  'Use the token from inspect-tool-leases to release abandoned Mobile Serena/Playwright borrowers.' \
5996
+ 'gestalt scratch inspect-publication --cwd ROOT' \
5997
+ 'gestalt scratch recover-publication --cwd ROOT --expect TOKEN --confirm-quiescent' \
5998
+ 'Use the token from inspect-publication to clear an abandoned empty workspace publication fence.' \
5727
5999
  'Never use these overrides on a live session. Payload and provider history are retained.'
5728
6000
  else
5729
6001
  require_command node
@@ -0,0 +1,17 @@
1
+ /* Original Gestalt implementation. SPDX-License-Identifier: MIT
2
+ * Copyright (c) 2026 Dyne.org contributors.
3
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ * of this software and associated documentation files (the "Software"), to deal
5
+ * in the Software without restriction, including without limitation the rights
6
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ * of the Software, and to permit persons to whom the Software is furnished to do
8
+ * so, subject to the following conditions: The above copyright notice and this
9
+ * permission notice shall be included in all copies or substantial portions of
10
+ * the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
13
+ * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
14
+ * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
15
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
16
+ * DEALINGS IN THE SOFTWARE.
17
+ */