#!/usr/bin/env bash
# Manage the isolated Gestalt Codex profile and Gestalt Mobile installation.
set -Eeuo pipefail
IFS=$'\n\t'

readonly GESTALT_CLI_VERSION='0.16.1'
readonly DEFAULT_INSTALL_BASE_URL='https://dyne.github.io/gestalt'
readonly DEFAULT_MARKETPLACE='dyne/gestalt-agents'
readonly DEFAULT_MARKETPLACE_NAME='dyne-gestalt-agents'
readonly SUPERVISION_CAPABILITY_SCHEMA=1
readonly SUPERVISION_CONTRACT_VERSION=1
readonly MANAGED_SERENA_VERSION='1.7.0'
readonly MANAGED_UV_VERSION='0.12.23'
readonly DEFAULT_SKILLS_SOURCE='https://github.com/dyne/gestalt-skills'
readonly DEFAULT_SKILLS_REF='main'
serena_install_candidate=''
serena_install_lock=''
serena_install_process_pid=''
manager_update_temp_root=''
manager_update_staged_target=''
manager_update_resumed=false
update_restart_lock=''
skills_transfer_temp_root=''
skills_export_staged_target=''
doctor_sandbox_report=''
codex_approval_launcher=''

log() {
  printf 'gestalt: %s\n' "$*" >&2
}

die() {
  log "error: $*"
  exit 1
}

on_error() {
  local -r exit_code=$?
  local -r line_number=${1:-unknown}
  log "command failed near line ${line_number} (exit ${exit_code})"
  exit "$exit_code"
}
trap 'on_error "$LINENO"' ERR

cleanup() {
  if [[ -n $serena_install_process_pid ]]; then
    kill -TERM "$serena_install_process_pid" 2>/dev/null || true
    wait "$serena_install_process_pid" 2>/dev/null || true
  fi
  if [[ -n $serena_install_candidate && -d $serena_install_candidate ]]; then
    # A signal between atomic promotion and clearing the flag must preserve the active release.
    if node - "$gestalt_home/serena/active.json" "$serena_install_candidate" <<'JS'
const fs=require('node:fs');
try {const d=JSON.parse(fs.readFileSync(process.argv[2],'utf8'));process.exit(d.executable===process.argv[3]+'/bin/serena'?1:0);}
catch(error){process.exit(error.code==='ENOENT'?0:1);}
JS
    then
      rm -rf -- "$serena_install_candidate"
    fi
  fi
  if [[ -n $serena_install_lock && -d $serena_install_lock ]]; then
    rmdir -- "$serena_install_lock" 2>/dev/null || true
  fi
  if [[ -n $manager_update_temp_root && -d $manager_update_temp_root ]]; then
    rm -rf -- "$manager_update_temp_root"
  fi
  if [[ -n $manager_update_staged_target && -f $manager_update_staged_target ]]; then
    rm -f -- "$manager_update_staged_target"
  fi
  if [[ -n $update_restart_lock && -d $update_restart_lock ]]; then
    rmdir -- "$update_restart_lock" 2>/dev/null || true
  fi
  if [[ -n $skills_transfer_temp_root && -d $skills_transfer_temp_root ]]; then
    rm -rf -- "$skills_transfer_temp_root"
  fi
  if [[ -n $skills_export_staged_target && -f $skills_export_staged_target ]]; then
    rm -f -- "$skills_export_staged_target"
  fi
}
trap cleanup EXIT

# Kept in the distributed manager: installed launchers have no adjacent modules.
session_scratch_runtime() {
  cat <<'SCRATCH_JS'
// BEGIN SESSION SCRATCH RUNTIME
const scratchFs = require('node:fs');
const scratchPath = require('node:path');
const scratchCrypto = require('node:crypto');
const scratchVariable = 'GESTALT_SESSION_TMP_CONTEXT';
const scratchNames = [scratchVariable, 'TMPDIR', 'TMP', 'TEMP'];

const scratchId = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(value);
const scratchUuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
function scratchAssert(condition) { if (!condition) throw Error('SESSION_SCRATCH_INVALID_CONTEXT'); }
function scratchCanonical(directory) {
  scratchAssert(typeof directory === 'string' && scratchPath.isAbsolute(directory) &&
    !/[\x00-\x1f\x7f]/.test(directory) && scratchPath.resolve(directory) === directory);
  let current = scratchPath.parse(directory).root;
  for (const component of directory.slice(current.length).split('/').filter(Boolean)) {
    current = scratchPath.join(current, component);
    const info = scratchFs.lstatSync(current);
    scratchAssert(info.isDirectory() && !info.isSymbolicLink());
  }
  scratchAssert(scratchFs.realpathSync(directory) === directory);
}
function scratchPrivate(directory) {
  scratchCanonical(directory);
  const info = scratchFs.lstatSync(directory);
  scratchAssert((!process.getuid || info.uid === process.getuid()) &&
    (process.platform === 'win32' || (info.mode & 0o777) === 0o700));
}
function scratchJson(file) {
  const fd = scratchFs.openSync(file, scratchFs.constants.O_RDONLY | scratchFs.constants.O_NOFOLLOW);
  try {
    const info = scratchFs.fstatSync(fd);
    scratchAssert(info.isFile() && info.nlink === 1 && info.size <= 16384 &&
      (!process.getuid || info.uid === process.getuid()) &&
      (process.platform === 'win32' || (info.mode & 0o077) === 0));
    return JSON.parse(scratchFs.readFileSync(fd, 'utf8'));
  } finally { scratchFs.closeSync(fd); }
}
function scratchRuntimeContainer() {
  scratchAssert(typeof process.getuid === 'function');
  return scratchPath.join(scratchFs.realpathSync('/tmp'), 'gs-' + process.getuid());
}
function scratchRuntimeIdentity(directory) {
  scratchPrivate(directory);
  const info = scratchFs.lstatSync(directory, {bigint:true});
  return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
}
function scratchRuntimeRecord(owner, runtime) {
  return {schemaVersion:2,ownerId:owner.ownerId,workspacePath:owner.workspacePath,token:runtime.token,identity:runtime.identity};
}
function scratchAllocateRuntime(owner) {
  const container = scratchRuntimeContainer();
  try {scratchFs.mkdirSync(container,{mode:0o700});} catch(error) {if(error.code!=='EEXIST')throw error;}
  scratchPrivate(container);
  for(let attempt=0;attempt<16;attempt++) {
    const directory=scratchPath.join(container,scratchCrypto.randomBytes(10).toString('hex'));
    if(Buffer.byteLength(directory)>48)throw Error('SESSION_SCRATCH_RUNTIME_ROOT_TOO_LONG');
    try {scratchFs.mkdirSync(directory,{mode:0o700});} catch(error) {if(error.code==='EEXIST')continue;throw error;}
    const runtime={directory,token:scratchCrypto.randomBytes(32).toString('hex'),identity:scratchRuntimeIdentity(directory)};
    scratchPublish(scratchPath.join(directory,'.gestalt-runtime.json'),scratchRuntimeRecord(owner,runtime),true);
    return runtime;
  }
  throw Error('SESSION_SCRATCH_RUNTIME_COLLISION');
}
function scratchValidateRuntime(owner,runtime) {
  const container=scratchRuntimeContainer();
  scratchAssert(runtime && typeof runtime.directory==='string' && scratchPath.dirname(runtime.directory)===container &&
    /^[0-9a-f]{20}$/.test(scratchPath.basename(runtime.directory)) && Buffer.byteLength(runtime.directory)<=48 &&
    typeof runtime.token==='string' && /^[0-9a-f]{64}$/.test(runtime.token) &&
    typeof runtime.identity==='string' && /^\d+:\d+:\d+$/.test(runtime.identity) && runtime.retiring===undefined);
  scratchPrivate(container);
  scratchAssert(scratchRuntimeIdentity(runtime.directory)===runtime.identity &&
    JSON.stringify(scratchJson(scratchPath.join(runtime.directory,'.gestalt-runtime.json')))===JSON.stringify(scratchRuntimeRecord(owner,runtime)));
}
function scratchTemporaryDirectory(context) {return context.runtime?.directory ?? context.directory;}
function scratchSocketPath(endpoint,capacity=({linux:108,darwin:104})[process.platform]) {
  if(!capacity)throw Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
  if(endpoint.includes('\0') || Buffer.byteLength(endpoint)+1>capacity)
    throw Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name or temporary root');
  return endpoint;
}
function scratchWorkspacePublication(workspace,publish) {
  scratchCanonical(workspace);
  const path=scratchPath.join(workspace,'.gestalt-scratch-lock');
  let claimed=false;
  for(let attempt=0;attempt<100;attempt++) {
    try {scratchFs.mkdirSync(path,{mode:0o700});claimed=true;break;}
    catch(error){if(error.code!=='EEXIST')throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10);}
  }
  if(!claimed)throw Error('SESSION_SCRATCH_BUSY');
  scratchPrivate(path);
  const fd=scratchFs.openSync(path,scratchFs.constants.O_RDONLY|scratchFs.constants.O_DIRECTORY|scratchFs.constants.O_NOFOLLOW);
  const held=scratchFs.fstatSync(fd,{bigint:true});
  try {
    const parents=scratchManagedAncestors(workspace).map(ancestor=>ancestor.context.workspacePath);
    scratchCheckParentPublications(workspace,parents);
    const result=publish();
    scratchCheckParentPublications(workspace,parents);
    return result;
  }
  finally {
    try {
      const current=scratchFs.lstatSync(path,{bigint:true});
      scratchAssert(current.isDirectory() && !current.isSymbolicLink() && current.dev===held.dev && current.ino===held.ino && current.birthtimeNs===held.birthtimeNs);
      scratchFs.rmdirSync(path);
    } finally {scratchFs.closeSync(fd);}
  }
}
function scratchCheckParentPublications(workspace,logicalParents=[]) {
  const parents=new Set(logicalParents);let current=scratchPath.parse(workspace).root;
  for(const part of workspace.slice(current.length).split(scratchPath.sep).filter(Boolean)) {
    current=scratchPath.join(current,part);if(part==='tmp')parents.add(scratchPath.dirname(current));
  }
  parents.delete(workspace);
  for(const parent of parents) {
    try{scratchFs.lstatSync(scratchPath.join(parent,'.gestalt-scratch-lock'));}
    catch(error){if(error.code==='ENOENT')continue;throw error;}
    throw Error('SESSION_SCRATCH_BUSY');
  }
}
function scratchContext(environment = process.env, allowReleased = false) {
  if (!Object.hasOwn(environment, scratchVariable)) return null;
  const context = JSON.parse(environment[scratchVariable]);
  scratchAssert([1,2].includes(context?.schemaVersion) && scratchId(context.ownerId));
  scratchCanonical(context.workspacePath);
  const container = scratchPath.join(context.workspacePath, 'tmp', 'sessions');
  scratchAssert(context.directory === scratchPath.join(container, context.ownerId) &&
    context.markerPath === scratchPath.join(context.directory, '.gestalt-owner.json'));
  // tmp may already contain user files/rules. Match the producer's parent
  // check without changing its existing permissions; managed descendants alone
  // require 0700.
  const parent = scratchPath.dirname(container);
  scratchCanonical(parent);
  scratchAssert(!process.getuid || scratchFs.lstatSync(parent).uid === process.getuid());
  for (const directory of [container, context.directory]) scratchPrivate(directory);
  const marker = scratchJson(context.markerPath);
  scratchAssert(marker?.schemaVersion === context.schemaVersion && marker.ownerId === context.ownerId &&
    marker.workspacePath === context.workspacePath && scratchId(marker.sessionId) &&
    typeof marker.createdAt === 'string' && Number.isFinite(Date.parse(marker.createdAt)) &&
    Array.isArray(marker.providerThreads) && marker.providerThreads.every(thread =>
      ['codex', 'kimi'].includes(thread?.provider) && scratchId(thread.threadId)));
  if(context.schemaVersion===2) {
    scratchAssert(JSON.stringify(context.runtime)===JSON.stringify(marker.runtime));
    scratchValidateRuntime(marker,marker.runtime);
  } else scratchAssert(context.runtime===undefined && marker.runtime===undefined);
  if (marker.ownerKind === 'mobile-session') {
    scratchAssert(context.ownerId === 'mobile-' + scratchCrypto.createHash('sha256').update(marker.sessionId).digest('hex') &&
      marker.authority?.kind === 'mobile-roster' && marker.authority.sessionId === marker.sessionId);
  } else {
    const prefix = marker.ownerKind === 'cli-session' ? 'cli-' : marker.ownerKind === 'workspace-service' ? 'service-' : '';
    scratchAssert(prefix && context.ownerId.startsWith(prefix) && scratchUuid(context.ownerId.slice(prefix.length)) &&
      marker.sessionId === context.ownerId && marker.authority?.kind === 'lease' && scratchUuid(marker.authority.leaseId));
    const leases = scratchPath.join(context.directory, 'leases');
    scratchPrivate(leases);
    const lease = scratchJson(scratchPath.join(leases, marker.authority.leaseId + '.json'));
    scratchAssert(lease?.schemaVersion === 1 && lease.ownerId === context.ownerId && lease.workspacePath === context.workspacePath &&
      lease.leaseId === marker.authority.leaseId && (lease.state === 'active' || allowReleased && lease.state === 'released') && scratchUuid(lease.processIdentity) &&
      typeof lease.createdAt === 'string' && Number.isFinite(Date.parse(lease.createdAt)) &&
      typeof lease.updatedAt === 'string' && Number.isFinite(Date.parse(lease.updatedAt)) &&
      Array.isArray(lease.consumers) && lease.consumers.every(scratchId));
  }
  return context;
}
function scratchEnvironment(environment = process.env) {
  const context = scratchContext(environment);
  const directory=context && scratchTemporaryDirectory(context);
  return context ? { ...environment, TMPDIR: directory, TMP: directory, TEMP: directory } : { ...environment };
}
function scratchDiscoveryEnvironment(environment = process.env) {
  const result = { ...environment };
  if (Object.hasOwn(result, scratchVariable)) for (const name of scratchNames) delete result[name];
  return result;
}
function scratchPublish(file, value, initial = false) {
  const staged = initial ? file : scratchPath.join(scratchPath.dirname(file), '.' + scratchCrypto.randomUUID() + '.json');
  const fd = scratchFs.openSync(staged, 'wx', 0o600);
  try { scratchFs.writeFileSync(fd, JSON.stringify(value) + '\n'); scratchFs.fsyncSync(fd); }
  finally { scratchFs.closeSync(fd); }
  if (!initial) scratchFs.renameSync(staged, file);
}
function scratchContainer(workspace) {
  scratchCanonical(workspace);
  const parent = scratchPath.join(workspace, 'tmp');
  try { scratchFs.mkdirSync(parent, {mode: 0o700}); } catch (e) { if (e.code !== 'EEXIST') throw e; }
  scratchCanonical(parent);
  scratchAssert(!process.getuid || scratchFs.lstatSync(parent).uid === process.getuid());
  const container = scratchPath.join(parent, 'sessions');
  try { scratchFs.mkdirSync(container, {mode: 0o700}); } catch (e) { if (e.code !== 'EEXIST') throw e; }
  scratchPrivate(container);
  try { scratchFs.writeFileSync(scratchPath.join(container, '.gitignore'), '*\n', {mode: 0o600, flag: 'wx'}); }
  catch (e) { if (e.code !== 'EEXIST') throw e; }
  return container;
}
function scratchOwnerContext(workspace, ownerId) {
  const directory = scratchPath.join(workspace, 'tmp', 'sessions', ownerId);
  const context={schemaVersion:1,workspacePath:workspace,ownerId,directory,markerPath:scratchPath.join(directory,'.gestalt-owner.json')};
  try {const marker=scratchJson(context.markerPath);if(marker.schemaVersion===2){context.schemaVersion=2;context.runtime=marker.runtime;}}
  catch(error){if(error.code!=='ENOENT')throw error;}
  return context;
}
function scratchLeaseRecords(context) {
  const directory = scratchPath.join(context.directory, 'leases');
  scratchPrivate(directory);
  return scratchFs.readdirSync(directory).map(name => {
    scratchAssert(scratchUuid(name.replace(/\.json$/, '')) && name.endsWith('.json'));
    const value = scratchJson(scratchPath.join(directory, name));
    scratchAssert(value?.schemaVersion === 1 && value.ownerId === context.ownerId && value.workspacePath === context.workspacePath &&
      name === value.leaseId + '.json' && ['active', 'released'].includes(value.state) && scratchUuid(value.processIdentity) &&
      typeof value.createdAt === 'string' && Number.isFinite(Date.parse(value.createdAt)) &&
      typeof value.updatedAt === 'string' && Number.isFinite(Date.parse(value.updatedAt)) &&
      Array.isArray(value.consumers) && value.consumers.every(scratchId) && (value.state !== 'released' || value.consumers.length === 0));
    return value;
  });
}
function scratchDirectoryIdentity(directory) {
  const info = scratchFs.lstatSync(directory, {bigint: true});
  scratchAssert(info.isDirectory() && !info.isSymbolicLink());
  return {dev: info.dev, ino: info.ino, birth: info.birthtimeNs};
}
function scratchSameDirectory(left, right) {
  return left.dev === right.dev && left.ino === right.ino && left.birth === right.birth;
}
function scratchAncestorOwner(context) {
  // Released CLI/service ancestors still have positive attribution. This read
  // grants no cleanup authority and never expires a lease or steals a fence.
  scratchContext({[scratchVariable]: JSON.stringify(context)}, true);
  const marker = scratchJson(context.markerPath);
  try {
    scratchFs.lstatSync(scratchPath.join(context.directory, 'leases'));
    scratchLeaseRecords(context);
  } catch (error) {if (error.code !== 'ENOENT' || marker.ownerKind !== 'mobile-session') throw error;}
  return {
    context, identity: scratchDirectoryIdentity(context.directory),
    provenance: JSON.stringify([marker.schemaVersion, marker.ownerKind, marker.ownerId, marker.workspacePath,
      marker.sessionId, marker.createdAt, marker.authority.kind, marker.authority.sessionId ?? null, marker.authority.leaseId ?? null, marker.runtime ?? null]),
  };
}
function scratchManagedAncestors(workspace, ancestors=[], visiting=new Set()) {
  scratchAssert(!visiting.has(workspace) && visiting.size<64);
  visiting.add(workspace);
  const parts = workspace.slice(scratchPath.parse(workspace).root.length).split(scratchPath.sep).filter(Boolean);
  const runtimeBase=process.getuid?scratchRuntimeContainer():undefined;
  let directory = scratchPath.parse(workspace).root;
  for (let i = 0; i < parts.length; i++) {
    directory = scratchPath.join(directory, parts[i]);
    if(runtimeBase && scratchPath.dirname(directory)===runtimeBase) {
      scratchPrivate(directory);
      const locator=scratchJson(scratchPath.join(directory,'.gestalt-runtime.json'));
      scratchAssert(typeof locator.workspacePath==='string' && scratchId(locator.ownerId));
      const owner=scratchOwnerContext(locator.workspacePath,locator.ownerId);
      scratchContext({[scratchVariable]:JSON.stringify(owner)},true);
      scratchAssert(owner.runtime?.directory===directory);
      scratchManagedAncestors(owner.directory,ancestors,visiting);
    }
    if (i >= 2 && parts[i - 1] === 'sessions' && parts[i - 2] === 'tmp') {
      if(ancestors.some(ancestor=>ancestor.context.directory===directory))continue;
      scratchAssert(ancestors.length<64);
      const ownerWorkspace = scratchPath.dirname(scratchPath.dirname(scratchPath.dirname(directory)));
      ancestors.push(scratchAncestorOwner(scratchOwnerContext(ownerWorkspace, parts[i])));
    }
  }
  visiting.delete(workspace);
  return ancestors;
}
function scratchRevalidateAncestor(ancestor) {
  const current = scratchAncestorOwner(ancestor.context);
  scratchAssert(scratchSameDirectory(ancestor.identity, current.identity) && ancestor.provenance === current.provenance);
}
// Offline operator recovery only. An empty directory supplies no evidence that
// its publisher died, so normal allocation must never invoke this override.
function scratchContainmentSnapshot(workspace, ownerId) {
  scratchAssert(scratchId(ownerId));
  const context = scratchOwnerContext(workspace, ownerId);
  const ancestor = scratchAncestorOwner(context);
  scratchAssert(scratchJson(context.markerPath).ownerKind === 'mobile-session');
  const path = scratchPath.join(context.directory, '.containment-lock');
  const expected = scratchDirectoryIdentity(path);
  scratchPrivate(path);
  scratchAssert(scratchFs.readdirSync(path).length === 0);
  // Other metadata writers must be quiescent too; their claims are never
  // cleared by containment recovery, regardless of age or apparent PID state.
  for (const name of ['.controller-lock', '.association-lock']) {
    try {scratchFs.lstatSync(scratchPath.join(context.directory, name));}
    catch (error) {if (error.code === 'ENOENT') continue; throw error;}
    throw new Error('SESSION_SCRATCH_RECOVERY_WRITER_BUSY');
  }
  const token = scratchCrypto.createHash('sha256').update(JSON.stringify({
    owner: ancestor.provenance,
    ownerIdentity: ancestor.identity,
    marker: scratchJson(context.markerPath),
    leases: scratchFs.existsSync(scratchPath.join(context.directory, 'leases'))
      ? scratchLeaseRecords(context).sort((left, right) => left.leaseId.localeCompare(right.leaseId)) : [],
    lockIdentity: expected,
  }, (_, value) => typeof value === 'bigint' ? value.toString() : value)).digest('hex');
  return {context, ancestor, path, expected, token};
}
function scratchRecoverContainment(workspace, ownerId, token) {
  scratchAssert(typeof token === 'string' && /^[a-f0-9]{64}$/.test(token));
  const snapshot = scratchContainmentSnapshot(workspace, ownerId);
  if (snapshot.token !== token) throw new Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
  const fd = scratchFs.openSync(snapshot.path, scratchFs.constants.O_RDONLY | scratchFs.constants.O_DIRECTORY | scratchFs.constants.O_NOFOLLOW);
  try {
    const held = scratchFs.fstatSync(fd, {bigint: true});
    scratchAssert(scratchSameDirectory(snapshot.expected, {dev: held.dev, ino: held.ino, birth: held.birthtimeNs}));
    scratchRevalidateAncestor(snapshot.ancestor);
    // Recheck after opening. This is explicitly offline recovery, not a claim
    // that check-then-rmdir is safe against a concurrent cooperating writer.
    const current = scratchContainmentSnapshot(workspace, ownerId);
    if (current.token !== token) throw new Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
    scratchFs.rmdirSync(snapshot.path); // Empty only; never recursive.
  } finally {scratchFs.closeSync(fd);}
}
// A closed roster row cannot prove detached tool exit. These legacy leases
// have no durable process handle; only an explicit offline operator assertion
// can retire them. Normal allocation, shutdown and cleanup never call this.
function scratchToolLeaseSnapshot(workspace, ownerId) {
  scratchAssert(scratchId(ownerId));
  const context = scratchOwnerContext(workspace, ownerId);
  const ancestor = scratchAncestorOwner(context);
  const marker = scratchJson(context.markerPath);
  scratchAssert(marker.ownerKind === 'mobile-session');
  for (const name of ['.controller-lock', '.association-lock', '.containment-lock']) {
    try {scratchFs.lstatSync(scratchPath.join(context.directory, name));}
    catch (error) {if (error.code === 'ENOENT') continue; throw error;}
    throw new Error('SESSION_SCRATCH_RECOVERY_WRITER_BUSY');
  }
  const directory = scratchPath.join(context.directory, 'leases');
  const leases = scratchLeaseRecords(context).sort((a, b) => a.leaseId.localeCompare(b.leaseId));
  const active = leases.filter(lease => lease.state === 'active');
  scratchAssert(active.length > 0 && active.every(lease => lease.consumers.length === 1 &&
    ['serena-mcp', 'playwright-mcp'].includes(lease.consumers[0])));
  const fileIdentity = path => {
    const info = scratchFs.lstatSync(path, {bigint: true});
    return {dev: info.dev, ino: info.ino, birth: info.birthtimeNs};
  };
  const token = scratchCrypto.createHash('sha256').update(JSON.stringify({
    kind: 'mobile-tool-leases', owner: ancestor.provenance, ownerIdentity: ancestor.identity,
    marker, markerIdentity: fileIdentity(context.markerPath),
    leaseDirectory: scratchDirectoryIdentity(directory),
    leases: leases.map(lease => ({lease, identity: fileIdentity(scratchPath.join(directory, lease.leaseId + '.json'))})),
  }, (_, value) => typeof value === 'bigint' ? value.toString() : value)).digest('hex');
  return {context, active, token};
}
function scratchRecoverToolLeases(workspace, ownerId, token) {
  scratchAssert(typeof token === 'string' && /^[a-f0-9]{64}$/.test(token));
  const snapshot = scratchToolLeaseSnapshot(workspace, ownerId);
  if (snapshot.token !== token) throw new Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
  // Recheck the entire inspected set before publishing any changes. This is
  // offline recovery, not synchronization with a running metadata writer.
  if (scratchToolLeaseSnapshot(workspace, ownerId).token !== token)
    throw new Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
  for (const lease of snapshot.active) {
    scratchPublish(scratchPath.join(snapshot.context.directory, 'leases', lease.leaseId + '.json'),
      {...lease, state: 'released', consumers: [], updatedAt: new Date().toISOString()});
  }
}
// Offline-only publication recovery also works when allocation never reached an owner.
function scratchPublicationSnapshot(workspace) {
  scratchCanonical(workspace);
  const path=scratchPath.join(workspace,'.gestalt-scratch-lock');
  scratchPrivate(path);
  scratchAssert(scratchFs.readdirSync(path).length===0);
  const expected=scratchDirectoryIdentity(path);
  const token=scratchCrypto.createHash('sha256').update(JSON.stringify({
    workspace:scratchDirectoryIdentity(workspace),lock:expected,
    ancestors:scratchManagedAncestors(workspace).map(ancestor=>({
      owner:ancestor.provenance,identity:ancestor.identity,
      leases:scratchFs.existsSync(scratchPath.join(ancestor.context.directory,'leases'))
        ? scratchLeaseRecords(ancestor.context).sort((a,b)=>a.leaseId.localeCompare(b.leaseId)):[],
    })),
  },(_,value)=>typeof value==='bigint'?value.toString():value)).digest('hex');
  return {path,expected,token};
}
function scratchRecoverPublication(workspace,token) {
  scratchAssert(typeof token==='string' && /^[a-f0-9]{64}$/.test(token));
  const snapshot=scratchPublicationSnapshot(workspace);
  if(snapshot.token!==token)throw Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
  const fd=scratchFs.openSync(snapshot.path,scratchFs.constants.O_RDONLY|scratchFs.constants.O_DIRECTORY|scratchFs.constants.O_NOFOLLOW);
  try {
    const held=scratchFs.fstatSync(fd,{bigint:true});
    scratchAssert(scratchSameDirectory(snapshot.expected,{dev:held.dev,ino:held.ino,birth:held.birthtimeNs}));
    if(scratchPublicationSnapshot(workspace).token!==token)throw Error('SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED');
    scratchFs.rmdirSync(snapshot.path);
  } finally {scratchFs.closeSync(fd);}
}
function scratchRecoveryCommand(args) {
  const [action, ...options] = args;
  scratchAssert(['inspect', 'recover', 'inspect-tool-leases', 'recover-tool-leases', 'inspect-publication', 'recover-publication'].includes(action));
  const values = {};
  let confirmed = false;
  for (let index = 0; index < options.length; index++) {
    const name = options[index];
    if (name === '--confirm-quiescent') {scratchAssert(!confirmed); confirmed = true; continue;}
    scratchAssert(['--cwd', '--owner', '--expect'].includes(name) && !Object.hasOwn(values, name));
    scratchAssert(typeof options[index + 1] === 'string' && !options[index + 1].startsWith('--'));
    values[name] = options[++index];
  }
  scratchAssert(values['--cwd'] && (action.endsWith('-publication') ? !values['--owner'] : values['--owner']));
  if(action.endsWith('-publication')) {
    if(action==='inspect-publication') {
      scratchAssert(!confirmed && !values['--expect']);
      process.stdout.write(JSON.stringify({schemaVersion:1,status:'confirmationRequired',token:scratchPublicationSnapshot(values['--cwd']).token})+'\n');
    } else {
      scratchAssert(confirmed && values['--expect']);
      scratchRecoverPublication(values['--cwd'],values['--expect']);
      process.stdout.write(JSON.stringify({schemaVersion:1,status:'recovered'})+'\n');
    }
    return;
  }
  if (action === 'inspect' || action === 'inspect-tool-leases') {
    scratchAssert(!confirmed && !values['--expect']);
    const snapshot = action === 'inspect' ? scratchContainmentSnapshot(values['--cwd'], values['--owner'])
      : scratchToolLeaseSnapshot(values['--cwd'], values['--owner']);
    process.stdout.write(JSON.stringify({schemaVersion: 1, status: 'confirmationRequired', token: snapshot.token,
      ...(snapshot.active ? {activeToolLeases: snapshot.active.length} : {})}) + '\n');
  } else {
    scratchAssert(confirmed && values['--expect']);
    if (action === 'recover') scratchRecoverContainment(values['--cwd'], values['--owner'], values['--expect']);
    else scratchRecoverToolLeases(values['--cwd'], values['--owner'], values['--expect']);
    process.stdout.write(JSON.stringify({schemaVersion: 1, status: 'recovered'}) + '\n');
  }
}
function scratchWithContainment(workspace, publish) {
  return scratchWorkspacePublication(workspace,()=>{
  scratchCanonical(workspace);
  const selected = scratchDirectoryIdentity(workspace), ancestors = scratchManagedAncestors(workspace), claims = [];
  try {
    // Path traversal supplies outermost-first order. These short fences precede
    // new-owner controller/association work and never span a runtime lifetime.
    for (const ancestor of ancestors) {
      const path = scratchPath.join(ancestor.context.directory, '.containment-lock');
      try {scratchFs.mkdirSync(path, {mode: 0o700});}
      catch (error) {
        if (error.code === 'EEXIST') throw new Error('SESSION_SCRATCH_CONTAINMENT_BUSY');
        throw error;
      }
      const claim = {path, identity: scratchDirectoryIdentity(path), fd: undefined};
      claims.push(claim);
      scratchPrivate(path);
      claim.fd = scratchFs.openSync(path, scratchFs.constants.O_RDONLY | scratchFs.constants.O_DIRECTORY | scratchFs.constants.O_NOFOLLOW);
      const held = scratchFs.fstatSync(claim.fd, {bigint: true});
      scratchAssert(scratchSameDirectory(claim.identity, {dev: held.dev, ino: held.ino, birth: held.birthtimeNs}));
      scratchRevalidateAncestor(ancestor);
    }
    scratchCanonical(workspace);
    scratchAssert(scratchSameDirectory(selected, scratchDirectoryIdentity(workspace)));
    for (const ancestor of ancestors) scratchRevalidateAncestor(ancestor);
    // This publication callback is synchronous. No recursive workspace creation:
    // retirement or alias/identity changes
    // between discovery and fencing fail before scratchContainer publishes.
    return publish();
  } finally {
    let failure;
    for (const claim of claims.reverse()) {
      try {
        if (!scratchSameDirectory(claim.identity, scratchDirectoryIdentity(claim.path)))
          throw new Error('SESSION_SCRATCH_CONTAINMENT_FENCE_CHANGED');
        scratchFs.rmdirSync(claim.path);
      } catch (error) {failure ??= error;}
      finally {
        try {if (claim.fd !== undefined) scratchFs.closeSync(claim.fd);}
        catch (error) {failure ??= error;}
      }
    }
    if (failure) throw failure;
  }
  });
}
function scratchAllocate(workspace,kind,consumer) {
 scratchAssert(['cli-session','workspace-service'].includes(kind)&&scratchId(consumer));
 return scratchWithContainment(workspace,()=>{
 scratchContainer(workspace);
 const ownerId=(kind==='cli-session'?'cli-':'service-')+scratchCrypto.randomUUID(),context=scratchOwnerContext(workspace,ownerId);
 scratchFs.mkdirSync(context.directory,{mode:0o700});scratchPrivate(context.directory);
 const lock=scratchPath.join(context.directory,'.controller-lock');scratchFs.mkdirSync(lock,{mode:0o700});
 scratchFs.mkdirSync(scratchPath.join(context.directory,'leases'),{mode:0o700});
 const leaseId=scratchCrypto.randomUUID(),time=new Date().toISOString();
 const lease={schemaVersion:1,ownerId,workspacePath:workspace,leaseId,state:'active',processIdentity:scratchCrypto.randomUUID(),createdAt:time,updatedAt:time,consumers:[consumer]};
 const marker={schemaVersion:1,ownerKind:kind,ownerId,workspacePath:workspace,sessionId:ownerId,createdAt:time,authority:{kind:'lease',leaseId},providerThreads:[]};
 if(process.platform!=='win32') {
   marker.schemaVersion=2;marker.runtime=scratchAllocateRuntime(marker);
   context.schemaVersion=2;context.runtime=marker.runtime;
 }
 scratchPublish(scratchPath.join(context.directory,'leases',leaseId+'.json'),lease,true);scratchPublish(context.markerPath,marker,true);
 scratchContext({[scratchVariable]:JSON.stringify(context)});return {context,lease,lock};
 });
}
function scratchRelease(ownership) {
  const {context, lease, lock} = ownership;
  return scratchMetadata(context, () => {
  scratchPrivate(scratchPath.join(context.directory, 'leases'));
  // Unknown or unreleased borrowers protect the complete owner, not just one
  // process's view of it. Never use a PID or timestamp to retire another lease.
  if (!ownership.borrowed && scratchLeaseRecords(context).some(value => value.leaseId !== lease.leaseId && value.state !== 'released')) return false;
  const file = scratchPath.join(context.directory, 'leases', lease.leaseId + '.json');
  const current = scratchJson(file);
  scratchAssert(current.schemaVersion === 1 && current.ownerId === context.ownerId && current.workspacePath === context.workspacePath &&
    current.leaseId === lease.leaseId && current.processIdentity === lease.processIdentity && current.state === 'active' &&
    current.createdAt === lease.createdAt && typeof current.updatedAt === 'string' && Number.isFinite(Date.parse(current.updatedAt)) &&
    JSON.stringify(current.consumers) === JSON.stringify(lease.consumers));
  scratchPublish(file, {...current, state: 'released', consumers: [], updatedAt: new Date().toISOString()});
  if (!ownership.borrowed) {scratchPrivate(lock); scratchFs.rmdirSync(lock);}
  return true;
  });
}
function scratchMetadata(context, operation, waitMs = 0) {
  return scratchWorkspacePublication(context.workspacePath,()=>{
  scratchContext({[scratchVariable]: JSON.stringify(context)});
  const mobile = scratchJson(context.markerPath).ownerKind === 'mobile-session';
  // Mobile cleanup/association use this same controller fence. CLI/service
  // controllers already hold it for their lifetime and serialize borrowers
  // against primary release with the association fence instead.
  const lock = scratchPath.join(context.directory, mobile ? '.controller-lock' : '.association-lock');
  const deadline = Date.now() + waitMs;
  while (true) {
    try {scratchFs.mkdirSync(lock, {mode: 0o700}); break;} catch (error) {
      if (error.code !== 'EEXIST') throw error;
      if (Date.now() >= deadline) return false;
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
    }
  }
  try {
    scratchPrivate(lock);
    scratchContext({[scratchVariable]: JSON.stringify(context)});
    if (mobile) scratchAssert(!scratchFs.existsSync(scratchPath.join(context.directory, '.association-lock')));
    return operation();
  } finally {scratchFs.rmdirSync(lock);}
  });
}
function scratchBorrow(context, consumer) {
  scratchAssert(scratchId(consumer));
  const ownership = scratchMetadata(context, () => {
  const directory = scratchPath.join(context.directory, 'leases');
  try {scratchFs.mkdirSync(directory, {mode: 0o700});} catch (error) {if (error.code !== 'EEXIST') throw error;}
  scratchPrivate(directory);
  scratchLeaseRecords(context);
  const leaseId = scratchCrypto.randomUUID(), time = new Date().toISOString();
  const lease = {schemaVersion: 1, ownerId: context.ownerId, workspacePath: context.workspacePath, leaseId,
    state: 'active', processIdentity: scratchCrypto.randomUUID(), createdAt: time, updatedAt: time, consumers: [consumer]};
  scratchPublish(scratchPath.join(context.directory, 'leases', leaseId + '.json'), lease, true);
  return {context, lease, borrowed: true};
  }, 1000);
  scratchAssert(ownership);
  return ownership;
}
async function scratchReleaseReady(ownership) {
  const deadline = Date.now() + 3500;
  while (!scratchRelease(ownership)) {
    if (Date.now() >= deadline) return false;
    await scratchDelay(25);
  }
  return true;
}
// Source travels over stdin once; fd 4 remains the independent lifetime/input
// pipe. Neither source nor a nested supervisor program appears in argv or ps.
function scratchProgramBootstrap() {
  process.argv.splice(1, 2);
  process[Symbol.for('gestalt.stdin.fd')] = 4;
  const fs = require('node:fs');
  Object.defineProperty(process, 'stdin', {configurable: true, get() {
    const type = fs.fstatSync(4);
    const input = type.isFIFO() || type.isSocket()
      ? new (require('node:net').Socket)({fd: 4, readable: true, writable: false})
      : fs.createReadStream(null, {fd: 4});
    Object.defineProperty(process, 'stdin', {value: input, configurable: true});
    return input;
  }});
}
function scratchSpawnProgram(program, args, options = {}) {
  const {spawn} = require('node:child_process');
  const {label = 'gestalt-supervisor', ...settings} = options;
  const stdio = settings.stdio ?? ['pipe', 'inherit', 'inherit'];
  const child = spawn(process.execPath, ['--input-type=commonjs', '-', label],
    {...settings, stdio: ['pipe', stdio[1], stdio[2], stdio[3] ?? 'ignore', stdio[0]]});
  const source = child.stdin;
  child.stdin = child.stdio[4];
  source.on('error', () => {});
  source.end('(' + scratchProgramBootstrap.toString() + ')();\nprocess.argv.push(...' + JSON.stringify(args) + ');\n' + program);
  return child;
}
function scratchGuardianProgram(manager, consumer, lifetimeSupervisor = null) {
  const context = scratchContext();
  if (!context) return null;
  const ownership = scratchBorrow(context, consumer);
  const source = scratchFs.readFileSync(manager, 'utf8').match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
  scratchAssert(source);
  return source[1] + '\nconst args=JSON.parse(process.argv[2]);' +
    'scratchGuard('+JSON.stringify(ownership)+',process.argv[1],args,process.argv[3],'+JSON.stringify(lifetimeSupervisor)+',process.argv[4]||"").catch(()=>{process.stderr.write("gestalt: managed tool release unconfirmed; temporary owner protected\\n");process.exitCode=1;process.stdin.destroy();});';
}
function scratchAssociate(environment, threadId) {
  const context = scratchContext(environment);
  scratchAssert(context && scratchId(threadId));
  const lock = scratchPath.join(context.directory, '.association-lock'), deadline = Date.now() + 1000;
  while (true) {
    try {scratchFs.mkdirSync(lock, {mode: 0o700}); break;} catch (e) {
      if (e.code !== 'EEXIST' || Date.now() >= deadline) throw e;
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
    }
  }
  try {
    const marker = scratchJson(context.markerPath);
    scratchAssert(marker.ownerKind === 'cli-session');
    if (!marker.providerThreads.some(value => value.provider === 'codex' && value.threadId === threadId)) {
      const updated={...marker,providerThreads:[...marker.providerThreads,{provider:'codex',threadId}]};
      scratchPublish(context.markerPath,updated);
    }
  } finally {scratchFs.rmdirSync(lock);}
}
const scratchDelay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
function scratchGroupAbsent(pid) {
  if (!Number.isSafeInteger(pid) || pid < 2) return false;
  try { process.kill(-pid, 0); return false; } catch (e) { return e.code === 'ESRCH'; }
}
async function scratchStopped(child, stop = false, options = {}) {
  const running = () => child.exitCode === null && child.signalCode === null;
  const signal = name => {if (running() && child.pid) try {
    if (options.leaderFirst && name === 'SIGTERM') child.kill(name);
    else process.kill(-child.pid, name);
  } catch (e) {if (e.code !== 'ESRCH') throw e;}};
  if (stop) signal('SIGTERM');
  const deadline = Date.now() + (options.maxMs ?? 3500), escalation = Date.now() + (options.graceMs ?? 1500);
  while (Date.now() < deadline) {
    if (!running() && scratchGroupAbsent(child.pid)) return true;
    if (stop && Date.now() >= escalation) signal('SIGKILL');
    await scratchDelay(25);
  }
  // Leader exit permits read-only absence checks only. A cached numeric group
  // never authorizes a fresh termination signal after that boundary.
  return !running() && scratchGroupAbsent(child.pid);
}
async function scratchGuard(ownership, command, args, cwd, lifetimeSupervisor = null, staleToken = '') {
  const {spawn} = require('node:child_process');
  const environment = scratchEnvironment({...process.env, [scratchVariable]: JSON.stringify(ownership.context)});
  // Composed supervision retains a live group leader through consumer shutdown,
  // then terminates its owned descendants before the outer guardian releases.
  const composed = typeof lifetimeSupervisor === 'string';
  const child = composed
    ? scratchSpawnProgram(lifetimeSupervisor, [command, JSON.stringify(args), cwd, staleToken],
      {cwd, env: environment, detached: true, stdio: ['pipe', 'inherit', 'inherit', 3], label: 'gestalt-tool-lifetime'})
    : spawn(command, args, {cwd, env: environment, detached: true, stdio: [3, 'inherit', 'inherit']});
  if (composed) child.stdin.on('error', () => {});
  let stopping;
  const stop = code => stopping ??= (async () => {
    if (composed) child.stdin.end();
    const stopped = await scratchStopped(child, true, composed ? {leaderFirst: true, graceMs: 4000, maxMs: 6000} : {});
    if (stopped) await scratchReleaseReady(ownership);
    else process.stderr.write('gestalt: temporary owner remains protected; subprocess release is unconfirmed\n');
    process.exitCode = code;
    process.stdin.destroy();
  })();
  process.stdin.resume(); process.stdin.on('end', () => void stop(143));
  process.on('SIGTERM', () => void stop(143)); process.on('SIGINT', () => void stop(130));
  await new Promise(resolve => {child.once('error', () => resolve(127)); child.once('exit', code => resolve(code ?? 143));})
    .then(async code => {
      if (stopping) return stopping;
      stopping = (async () => {
        if (await scratchStopped(child)) await scratchReleaseReady(ownership);
        else process.stderr.write('gestalt: temporary owner remains protected; subprocess release is unconfirmed\n');
        process.exitCode = code; process.stdin.destroy();
      })();
      return stopping;
    });
}
async function scratchSupervise(manager, ownership, command, args) {
  const {spawn} = require('node:child_process');
  const source = scratchFs.readFileSync(manager, 'utf8').match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
  scratchAssert(source);
  const program = source[1] + '\nscratchGuard(JSON.parse(process.argv[1]),process.argv[2],JSON.parse(process.argv[3])).catch(()=>{process.stderr.write("gestalt: owned temporary lifetime failed; owner remains protected\\n");process.exitCode=1;process.stdin.destroy();});';
  // Separate lifetime pipe and original terminal/stdin: guardian EOF survives
  // an uncatchable controller exit and never consumes the native CLI's input.
  const guardian = scratchSpawnProgram(program, [JSON.stringify(ownership), command, JSON.stringify(args)],
    {stdio: ['pipe', 'inherit', 'inherit', process[Symbol.for('gestalt.stdin.fd')] ?? 0], label: 'gestalt-cli-lifetime'});
  guardian.stdin.on('error', () => {});
  for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => {
    if (guardian.exitCode === null && guardian.signalCode === null) guardian.kill(signal);
  });
  const code = await new Promise(resolve => {guardian.once('error', () => resolve(127)); guardian.once('exit', value => resolve(value ?? 143));});
  guardian.stdin.end(); process.exitCode = code;
}
async function scratchCli(manager, args) {
  let selected;
  for (let i = 0; i < args.length && args[i] !== '--'; i++) {
    const arg = args[i];
    if (['-c', '--config', '-p', '--profile', '--model', '-m', '--sandbox', '-s', '--ask-for-approval', '-a', '--image', '-i', '--permissions', '--remote', '--add-dir', '--local-provider'].includes(arg)) {i++; continue;}
    if (arg === '-C' || arg === '--cd') {scratchAssert(typeof args[i + 1] === 'string'); selected = scratchPath.resolve(selected ?? process.cwd(), args[++i]);}
    else if (arg.startsWith('--cd=')) selected = scratchPath.resolve(selected ?? process.cwd(), arg.slice(5));
    else if (arg.startsWith('-C') && arg.length > 2) selected = scratchPath.resolve(selected ?? process.cwd(), arg.slice(2));
  }
  if (!selected) {
    process.stderr.write('gestalt: no selected workspace; CLI temporary ownership unavailable (select with -C)\n');
    const {spawn} = require('node:child_process');
    const child = spawn('bash', [manager, '__cli-owned', ...args], {stdio: [process[Symbol.for('gestalt.stdin.fd')] ?? 0, 'inherit', 'inherit']});
    for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => child.kill(signal));
    process.exitCode = await new Promise(resolve => {child.once('error', () => resolve(127)); child.once('exit', value => resolve(value ?? 143));});
    return;
  }
  scratchCanonical(selected);
  // One invocation owns one stable UUID before native thread selection. Native
  // selectors, stdin and permission flags pass through without interception.
  const ownership = scratchAllocate(selected, 'cli-session', 'cli-controller');
  await scratchSupervise(manager, ownership, 'bash', [manager, '__cli-owned', ...args]);
}
// END SESSION SCRATCH RUNTIME
if (process.argv[1] === 'validate') {
  try {const context = scratchContext(); process.stdout.write(scratchJson(context.markerPath).ownerKind + '\n' + scratchTemporaryDirectory(context));}
  catch { process.stderr.write('gestalt: invalid managed session temporary context\n'); process.exitCode = 1; }
}
if (process.argv[1] === 'scratch') {
  try {scratchRecoveryCommand(process.argv.slice(2));}
  catch (error) {
    const code = ['SESSION_SCRATCH_RECOVERY_WRITER_BUSY', 'SESSION_SCRATCH_RECOVERY_SNAPSHOT_CHANGED'].includes(error.message)
      ? error.message : 'SESSION_SCRATCH_RECOVERY_REJECTED';
    process.stderr.write('gestalt: ' + code + '; see gestalt scratch --help\n'); process.exitCode = 1;
  }
}
if (process.argv[1] === 'cli') scratchCli(process.argv[2], process.argv.slice(3)).catch(() => {
  process.stderr.write('gestalt: managed CLI temporary ownership unavailable\n'); process.exitCode = 1;
});
if(process.argv[1]==='hook') {
 let input='';process.stdin.on('data',bytes=>{input+=bytes;if(input.length>16384)process.stdin.destroy();});
 process.stdin.on('end',()=>{try {
  const value=JSON.parse(input);scratchAssert(value.hook_event_name==='SubagentStart'||value.hook_event_name==='SessionStart'&&['startup','resume'].includes(value.source));
  scratchAssociate(process.env,value.hook_event_name==='SubagentStart'?value.agent_id:value.session_id);
 }catch{try{scratchBorrow(scratchContext(),'cli-provider-association-failed');}catch{}process.stderr.write('gestalt: CLI provider association failed; temporary owner remains protected\n');process.exitCode=1;}});
}
SCRATCH_JS
}

validate_session_tmp_context() {
  # Presence, including an empty value, must fail closed before state creation.
  if [[ ${GESTALT_SESSION_TMP_CONTEXT+x} ]]; then
    require_command node
    local session_directory validated
    validated=$(node -e "$(session_scratch_runtime)" validate) ||
      die 'managed session temporary context rejected'
    session_directory=${validated#*$'\n'}
    export TMPDIR="$session_directory" TMP="$session_directory" TEMP="$session_directory"
  fi
}

usage() {
  cat <<'EOF'
Usage: gestalt <command> [options]

Manage Gestalt Agents and Gestalt Mobile in isolated, user-owned directories.

Commands:
  install [--extra-skills]  Install or reconcile Agents, optional skills, and Mobile.
  agents install, update    Install or reconcile Agents and context-mode only.
  update [COMPONENT] [--extra-skills]
                            Update all installed managed components (default).
  update-restart [COMPONENT] [--extra-skills]
                            Update from a live Mobile session, then restart Mobile.
  cli [--] [args...]        Start Codex with ~/.codex-gestalt as CODEX_HOME.
  mobile [--] [args...]     Start the managed Gestalt Mobile executable.
  scratch inspect --cwd ROOT --owner ID
                            Inspect an empty Mobile containment fence (read-only).
  scratch recover --cwd ROOT --owner ID --expect TOKEN --confirm-quiescent
                            Offline recovery after all owner processes have stopped.
  playwright install [VERSION] Install MCP; add missing system Chrome on Debian amd64.
  playwright update [VERSION]  Stage, verify and activate an explicit package update.
  playwright version [--json]  Read versioned installation metadata.
  playwright doctor [--json] [--launch] [--executable-path PATH] Check package and Chrome; optionally test a local page.
  playwright mcp --cwd ROOT    Managed headless stdio (workspace profile).
  serena install            Install private uv, Python 3.13 and tested Serena.
  serena update [VERSION]   Validate and activate a release; retain prior tooling.
  serena version, -V        Read installed package metadata without creating state.
  serena doctor [--cwd ROOT] Check install, sandbox, MCP tools and optional language readiness.
  serena index --cwd ROOT    Explicit native symbol/cache warmup for one project.
  serena mcp --cwd ROOT      Confined workspace MCP; always Codex context and editing mode.
  path [NAME|--json]        Print managed executable and runtime paths.
  skills install, update   Maintain the optional Dyne.org skill collection only.
  skills status [--json]   Read installed version, revision and integrity.
  skills-export [ARCHIVE]   Export installed skills and skill profiles.
  skills-import ARCHIVE     Import a skills archive into this installation.
  doctor [--cwd ROOT]        Check prerequisites and installation.
  version                   Print manager and detected component versions.
  help                      Show this help.

Update components (also accepted as --component COMPONENT):
  all                       Gestalt core plus installed Serena and Playwright (default).
  gestalt                   Manager, Agents, Mobile, and context-mode runtime.
  serena                    Latest stable Serena and its private uv/Python tooling.
  playwright                Stable Playwright MCP package; Chrome is externally maintained.

Optional components absent from this installation are skipped by 'all'.
Selecting serena or playwright explicitly installs or updates that component only.
--extra-skills applies only to all or gestalt; it adds curated third-party skills.
Node, npm, Codex, Kimi, and system language servers are externally maintained.

Environment:
  CODEX_HOME                 Isolated Codex home (default: ~/.codex-gestalt).
  GESTALT_HOME               Runtime and Mobile root (default: ~/.gestalt).
  GESTALT_INSTALL_BASE_URL   Manager update source (default: https://dyne.github.io/gestalt).
  GESTALT_MARKETPLACE        Marketplace source (default: dyne/gestalt-agents).
  GESTALT_MARKETPLACE_NAME   Codex checkout name (default: dyne-gestalt-agents).
  GESTALT_MOBILE_VERSION     npm version or tag (default: latest).
  GESTALT_SKILLS_SOURCE      Collection source override (always unverified).
  GESTALT_SKILLS_REF         Collection Git ref or immutable revision (default: main).
EOF
}

# Reject lexical escapes and link traversal before allocating managed tooling.
validate_managed_tree_path() {
  local candidate=$1 part current=''
  local -a components=()
  [[ $candidate == /* && ! $candidate =~ [[:cntrl:]] ]] ||
    die 'managed paths must be absolute and contain no control characters'
  [[ $candidate != */ && $candidate != *//* ]] || die 'managed paths must be normalized'
  IFS='/' read -r -a components <<< "$candidate"
  for part in "${components[@]}"; do
    [[ -n $part ]] || continue
    [[ $part != . && $part != .. ]] || die 'managed paths cannot contain . or ..'
    current=$current/$part
    [[ ! -L $current ]] || die "managed path cannot traverse a symbolic link: $current"
  done
}

serena_workspace_prepare() {
  cat <<'PYTHON'
import sys, os, json, pathlib, tempfile, fcntl
sys.dont_write_bytecode = True
root = pathlib.Path(sys.argv[1])
executable = sys.argv[2]
settings = json.loads(sys.argv[3])
state = root / '.gestalt' / 'serena'
try:
    # Refuse redirected state before creating or importing anything that writes.
    for path in (root / '.gestalt', state):
        if path.is_symlink() or (path.exists() and not path.is_dir()):
            raise ValueError('workspace state must be a directory without symlinks')
    interpreter_targets = {pathlib.Path(settings['python']).resolve()}
    interpreter_targets.update(pathlib.Path(p).resolve() for p in settings.get('pythonExecutables', []))
    if state.exists():
        for directory, dirs, files in os.walk(state, followlinks=False):
            for name in dirs + files:
                path = pathlib.Path(directory) / name
                if path.is_symlink():
                    target = path.resolve()
                    interpreter_link = (path.name in {'python', 'python3', 'python3.13'} and path.parent.name == 'bin'
                        and (path.is_relative_to(state / 'uv-tools') or path.is_relative_to(state / 'uv-cache'))
                        and target in interpreter_targets)
                    if not target.is_relative_to(state) and not interpreter_link:
                        raise ValueError('workspace state contains an escaping symlink')
    state.mkdir(parents=True, exist_ok=True, mode=0o700)
    lock = open(state / '.prepare.lock', 'a')
    fcntl.flock(lock, fcntl.LOCK_EX)
    directories = ['home', 'tmp', 'uv-tools', 'uv-bin', 'uv-cache', 'xdg-cache', 'xdg-config',
                   'xdg-data', 'xdg-state', 'pycache', 'python-user', 'npm-cache', 'npm-prefix', 'clangd']
    for name in directories:
        (state / name).mkdir(exist_ok=True, mode=0o700)
    os.environ.update({
        'SERENA_HOME': str(state), 'SERENA_USAGE_REPORTING': 'false', 'HOME': str(state / 'home'),
        'TMPDIR': os.environ.get('TMPDIR', str(state / 'tmp')),
        'TMP': os.environ.get('TMP', os.environ.get('TMPDIR', str(state / 'tmp'))),
        'TEMP': os.environ.get('TEMP', os.environ.get('TMPDIR', str(state / 'tmp'))),
        'UV_TOOL_DIR': str(state / 'uv-tools'), 'UV_TOOL_BIN_DIR': str(state / 'uv-bin'),
        'UV_CACHE_DIR': str(state / 'uv-cache'), 'UV_PYTHON_INSTALL_DIR': settings['pythonInstallDir'],
        'UV_PYTHON_DOWNLOADS': 'never', 'PYTHONPYCACHEPREFIX': str(state / 'pycache'),
        'PYTHONUSERBASE': str(state / 'python-user'), 'PIP_CACHE_DIR': str(state / 'xdg-cache' / 'pip'),
        'XDG_CACHE_HOME': str(state / 'xdg-cache'), 'XDG_CONFIG_HOME': str(state / 'xdg-config'),
        'XDG_DATA_HOME': str(state / 'xdg-data'), 'XDG_STATE_HOME': str(state / 'xdg-state'),
        'npm_config_cache': str(state / 'npm-cache'), 'npm_config_prefix': str(state / 'npm-prefix'),
        'PATH': str(pathlib.Path(settings['uv']).parent) + os.pathsep + os.environ.get('PATH', ''),
    })
    from ruamel.yaml import YAML
    from serena.config.serena_config import SerenaConfig, ProjectConfig, ProjectConfigAutoGenerationMode
    yaml = YAML()
    def load(path):
        with open(path) as stream:
            value = yaml.load(stream)
        if not isinstance(value, dict):
            raise ValueError('invalid native Serena configuration')
        return value
    def save(path, value):
        if path.exists() and load(path) == value:
            return
        with tempfile.NamedTemporaryFile(mode='w', dir=state, delete=False) as stream:
            staged = stream.name
            yaml.dump(value, stream)
        os.replace(staged, path)
    # clangd stores project shards beside the selected compilation database,
    # independently of XDG_CACHE_HOME. Give each database a managed copy and
    # select it through workspace-local user configuration (no source edits).
    import hashlib, re
    fragments = []
    databases = []
    project_configs = []
    skipped = {'.git', '.gestalt', '.serena', '.cache', 'node_modules', '.venv'}
    for directory, dirs, files in os.walk(root, followlinks=False):
        dirs[:] = sorted(name for name in dirs if name not in skipped
                         and not (pathlib.Path(directory) / name).is_symlink())
        if '.clangd' in files:
            project_configs.append(pathlib.Path(directory) / '.clangd')
        if 'compile_commands.json' in files:
            databases.append(pathlib.Path(directory))
    # Broad scopes precede nested scopes. A root database takes precedence over
    # clangd's conventional build/ fallback for the same source directory.
    scopes = {}
    for directory in sorted(databases):
        scope = directory.parent if directory.name == 'build' else directory
        if scope not in scopes or directory == scope:
            scopes[scope] = directory
    def managed_database(scope, directory):
        try:
            source = directory / 'compile_commands.json'
            with open(source, encoding='utf-8') as stream:
                commands = json.load(stream)
            if not isinstance(commands, list):
                raise ValueError('compile_commands.json must contain an array')
            for entry in commands:
                if not isinstance(entry, dict) or not isinstance(entry.get('directory'), str):
                    raise ValueError('compile command requires a directory')
                working = pathlib.Path(entry['directory'])
                if not working.is_absolute():
                    entry['directory'] = str((directory / working).resolve())
        except (OSError, ValueError) as error:
            # clangd tolerates unusable databases; do not make an unrelated
            # fixture or incomplete build prevent Serena from starting.
            sys.stderr.write('gestalt: skipping clangd database ' + str(directory) + ': ' + str(error) + '\n')
            return str(directory)
        relative = os.path.relpath(directory, root)
        # Full relative-path identity prevents equal basenames from aliasing.
        identity = hashlib.sha256(relative.encode()).hexdigest()[:16]
        name = re.sub(r'[^A-Za-z0-9._-]', '_', scope.name) or 'source'
        managed = state / 'clangd' / (name + '-' + identity)
        database_dir = managed / 'database'
        cache = managed / 'cache'
        database_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
        cache.mkdir(exist_ok=True, mode=0o700)
        cache_link = database_dir / '.cache'
        if not cache_link.exists() and not cache_link.is_symlink():
            cache_link.symlink_to('../cache', target_is_directory=True)
        if not cache_link.is_symlink() or cache_link.resolve() != cache:
            raise ValueError('managed clangd cache link is invalid')
        target = database_dir / 'compile_commands.json'
        content = json.dumps(commands, ensure_ascii=False) + '\n'
        if not target.exists() or target.read_text(encoding='utf-8') != content:
            with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=database_dir, delete=False) as stream:
                staged = stream.name
                stream.write(content)
            os.replace(staged, target)
        return str(database_dir)
    for scope, directory in sorted(scopes.items(), key=lambda item: (len(item[0].parts), str(item[0]))):
        fragments.append({'If': {'PathMatch': re.escape(scope.as_posix()) + '/.*'},
                          'CompileFlags': {'CompilationDatabase': managed_database(scope, directory)}})
    # Reproduce explicit project database choices at user-config precedence.
    # Other project settings remain in their original fragments. Conditions in
    # project files are relative; user-config conditions must be absolute.
    for project_config in sorted(project_configs, key=lambda path: (len(path.parts), str(path))):
        try:
            with open(project_config, encoding='utf-8') as stream:
                documents = list(yaml.load_all(stream))
        except Exception as error:
            sys.stderr.write('gestalt: skipping clangd config ' + str(project_config) + ': ' + str(error) + '\n')
            continue
        for document in documents:
            if not isinstance(document, dict):
                continue
            choice = (document.get('CompileFlags') or {}).get('CompilationDatabase')
            if choice is None:
                continue
            scope = project_config.parent
            prefix = re.escape(scope.as_posix()) + '/'
            conditions = dict(document.get('If') or {})
            for key in ('PathMatch', 'PathExclude'):
                if key in conditions:
                    patterns = conditions[key]
                    if isinstance(patterns, str):
                        patterns = [patterns]
                    conditions[key] = [prefix + '(' + pattern + ')' for pattern in patterns]
            conditions.setdefault('PathMatch', prefix + '.*')
            if choice == 'Ancestors':
                # This is a dynamic lookup for each file, including nested
                # databases. Preserve it rather than freeze one build choice.
                fragments.append({'If': conditions, 'CompileFlags': {'CompilationDatabase': 'Ancestors'}})
                continue
            directory = (scope / str(choice)).resolve()
            selected = str(choice)
            if choice != 'None' and (directory / 'compile_commands.json').is_file():
                selected = managed_database(scope, directory)
            elif choice != 'None':
                selected = str(directory)
            fragments.append({'If': conditions, 'CompileFlags': {'CompilationDatabase': selected}})
    # Linux and macOS use different user-config discovery paths. Both stay
    # inside the managed HOME/XDG tree and carry the same generated fragments.
    begin = '# BEGIN GESTALT CLANGD DATABASES\n'
    end = '# END GESTALT CLANGD DATABASES\n'
    generated = begin + ''.join('---\n' + json.dumps(fragment) + '\n' for fragment in fragments) + end
    for config_path in (state / 'xdg-config/clangd/config.yaml',
                        state / 'home/Library/Preferences/clangd/config.yaml'):
        config_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        existing = config_path.read_text(encoding='utf-8') if config_path.exists() else ''
        if begin in existing:
            before, tail = existing.split(begin, 1)
            if end not in tail:
                raise ValueError('managed clangd configuration markers are invalid')
            remainder = tail.split(end, 1)[1]
            if remainder.startswith('---\n'):
                remainder = remainder[4:]
            existing = before + remainder
        content = generated + ('---\n' + existing.strip() + '\n' if existing.strip() else '')
        if not config_path.exists() or config_path.read_text(encoding='utf-8') != content:
            with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=state, delete=False) as stream:
                staged = stream.name
                stream.write(content)
            os.replace(staged, config_path)
    # Generate the release's own defaults, then apply only managed invariants.
    SerenaConfig.from_config_file()
    global_path = state / 'serena_config.yml'
    config = load(global_path)
    config['project_serena_folder_location'] = '$projectDir/.gestalt/serena'
    config['web_dashboard'] = False
    config['web_dashboard_open_on_launch'] = False
    config['gui_log_window'] = False
    config['trusted_project_path_patterns'] = []
    config['projects'] = [str(root)]
    config['ignored_paths'] = list(dict.fromkeys([*(config.get('ignored_paths') or []), '.gestalt/**']))
    ls = config.get('ls_specific_settings') or {}
    config['ls_specific_settings'] = ls
    ls.setdefault('cpp', {})['compile_commands_dir'] = '.gestalt/serena/clangd'
    config['excluded_tools'] = list(dict.fromkeys([*(config.get('excluded_tools') or []),
        'execute_shell_command', 'activate_project', 'switch_modes']))
    save(global_path, config)
    # Preserve legacy data in place. Only initialize the new native configuration
    # from existing project settings, never copy/move legacy memories or caches.
    for name in ('project.yml', 'project.local.yml'):
        destination, legacy = state / name, root / '.serena' / name
        if not destination.exists() and legacy.is_file():
            save(destination, load(legacy))
    native = SerenaConfig.from_config_file()
    project_path = state / 'project.yml'
    ProjectConfig.load(root, native, autogen=ProjectConfigAutoGenerationMode.SYNCHRONOUS)
    project = load(project_path)
    project['ignored_paths'] = list(dict.fromkeys([*(project.get('ignored_paths') or []), '.gestalt/**']))
    save(project_path, project)
    lock.close()
except Exception as error:
    sys.stderr.write('gestalt: Serena workspace preparation failed: ' + str(error) + '\n')
    sys.exit(1)
arguments = sys.argv[4:]
# Serena 2 defaults to REPL, which bypasses the individual tool contract.
# Use the CLI override so project configuration cannot select REPL instead.
# Older releases have neither this configuration field nor the CLI option.
if arguments[:1] == ['start-mcp-server'] and hasattr(SerenaConfig, 'agent_interface'):
    arguments += ['--agent-interface', 'tools']
os.execve(executable, [executable, *arguments], os.environ)
PYTHON
}

# Own native descendants independently of the SDK's detached stdio process.
serena_operator_supervisor() {
  cat <<'JS'
const {spawn}=require('node:child_process');
const child=spawn(process.argv[1],JSON.parse(process.argv[2]),{env:process.env,detached:true,stdio:['pipe','inherit','inherit']});
let ending=false,code=0;
function stop(){if(ending)return;ending=true;try{process.kill(-child.pid,'SIGTERM');}catch{}setTimeout(()=>{try{process.kill(-child.pid,'SIGKILL');}catch{}process.exit(code);},500);}
process.stdin.pipe(child.stdin);child.stdin.on('error',()=>{});
process.stdin.on('end',stop);process.on('SIGTERM',stop);process.on('SIGINT',stop);
child.on('error',()=>process.exit(1));child.on('exit',value=>{if(!ending)code=value??1;stop();});
JS
}

run_serena_install_process() {
  node --input-type=commonjs - "$@" <<'JS' &
process.argv.splice(1,1);
const {spawn}=require("node:child_process");
const child=spawn(process.argv[1],process.argv.slice(2),{env:process.env,detached:true,stdio:["ignore","inherit","inherit"]});
let ending=false,code=0;
function stop(){if(ending)return;ending=true;try{process.kill(-child.pid,"SIGTERM");}catch{}setTimeout(()=>{try{process.kill(-child.pid,"SIGKILL");}catch{}process.exit(code);},500);}
process.on("SIGTERM",()=>{code=143;stop();});process.on("SIGINT",()=>{code=130;stop();});
child.on("error",()=>process.exit(1));child.on("exit",value=>{if(!ending)code=value??1;stop();});
JS
  serena_install_process_pid=$!
  wait "$serena_install_process_pid"
  serena_install_process_pid=''
}

install_serena() {
  local version=${1:-$MANAGED_SERENA_VERSION} os cpu target asset base expected actual listing candidate
  [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die 'Serena release must be a stable VERSION (major.minor.patch)'
  require_command node
  require_command curl
  require_command tar
  require_command mktemp
  os=$(uname -s)
  cpu=$(uname -m)
  case $cpu in
    x86_64 | amd64) cpu=x86_64 ;;
    aarch64 | arm64) cpu=aarch64 ;;
    *) die "unsupported Serena CPU: $cpu" ;;
  esac
  case $os in
    Linux) target=$cpu-unknown-linux-gnu ;;
    Darwin) target=$cpu-apple-darwin ;;
    *) die "managed Serena supports Linux and macOS, not $os" ;;
  esac
  validate_managed_tree_path "$gestalt_home/serena"
  umask 077
  mkdir -p -- "$gestalt_home/serena"
  mkdir -- "$gestalt_home/serena/.install-lock" 2>/dev/null ||
    die 'Serena install already running (after a killed installer, verify it exited before removing .install-lock)'
  serena_install_lock=$gestalt_home/serena/.install-lock
  trap 'exit 130' INT
  trap 'exit 143' TERM
  # Construct at the final path: uv environments contain absolute interpreter paths.
  serena_install_candidate=$(mktemp -d "$gestalt_home/serena/release-$version.XXXXXXXX")
  candidate=$serena_install_candidate
  mkdir -- "$candidate/bin" "$candidate/home" "$candidate/tmp"
  asset=uv-$target.tar.gz
  base=https://github.com/astral-sh/uv/releases/download/$MANAGED_UV_VERSION
  curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
    --connect-timeout 20 --max-time 120 "$base/$asset" --output "$candidate/uv.tar.gz"
  curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
    --connect-timeout 20 --max-time 120 "$base/$asset.sha256" --output "$candidate/uv.sha256"
  IFS=' ' read -r expected _ < "$candidate/uv.sha256" || die 'missing uv checksum'
  [[ $expected =~ ^[[:xdigit:]]{64}$ ]] || die 'invalid uv checksum'
  actual=$(calculate_sha256 "$candidate/uv.tar.gz")
  actual=${actual%% *}
  actual=$(printf '%s' "$actual" | tr 'A-F' 'a-f')
  expected=$(printf '%s' "$expected" | tr 'A-F' 'a-f')
  [[ $actual == "$expected" ]] || die 'uv checksum mismatch; prior Serena installation preserved'
  unset TAR_OPTIONS GZIP
  listing=$(tar -tvzf "$candidate/uv.tar.gz" "uv-$target/uv")
  [[ $listing == -* && $listing != *$'\n'* ]] || die 'uv archive must contain one regular binary'
  tar -xOzf "$candidate/uv.tar.gz" "uv-$target/uv" > "$candidate/bin/uv"
  chmod 0755 "$candidate/bin/uv"
  case $("$candidate/bin/uv" --version) in
    "uv $MANAGED_UV_VERSION" | "uv $MANAGED_UV_VERSION ("*")") ;;
    *) die 'downloaded uv version mismatch' ;;
  esac
  # All installation writes are private. Never invoke the uv installer or modify profiles.
  run_serena_install_process env HOME="$candidate/home" TMPDIR="$candidate/tmp" UV_TOOL_DIR="$candidate/tools" \
    UV_TOOL_BIN_DIR="$candidate/bin" UV_CACHE_DIR="$candidate/cache" UV_PYTHON_INSTALL_DIR="$candidate/python" \
    UV_PYTHON_BIN_DIR="$candidate/bin" UV_NO_PROGRESS=1 UV_NO_CONFIG=1 \
    "$candidate/bin/uv" python install 3.13 --no-bin </dev/null
  run_serena_install_process env HOME="$candidate/home" TMPDIR="$candidate/tmp" UV_TOOL_DIR="$candidate/tools" \
    UV_TOOL_BIN_DIR="$candidate/bin" UV_CACHE_DIR="$candidate/cache" UV_PYTHON_INSTALL_DIR="$candidate/python" \
    UV_PYTHON_DOWNLOADS=never UV_NO_PROGRESS=1 UV_NO_CONFIG=1 \
    "$candidate/bin/uv" tool install --managed-python --python 3.13 "serena-agent==$version" </dev/null
  [[ -x $candidate/bin/serena && -x $candidate/tools/serena-agent/bin/python ]] || die 'Serena installation has missing executables'
  HOME="$candidate/home" TMPDIR="$candidate/tmp" SERENA_HOME="$candidate/probe" \
    GESTALT_SERENA_PREPARE="$(serena_workspace_prepare)" GESTALT_SERENA_NODE="$(command -v node)" \
    GESTALT_SERENA_SUPERVISOR="$(serena_operator_supervisor)" \
    PYTHONDONTWRITEBYTECODE=1 UV_TOOL_DIR="$candidate/tools" UV_TOOL_BIN_DIR="$candidate/bin" \
    UV_CACHE_DIR="$candidate/cache" UV_PYTHON_INSTALL_DIR="$candidate/python" UV_PYTHON_DOWNLOADS=never \
    "$candidate/tools/serena-agent/bin/python" - "$candidate" "$version" <<'PYTHON'
import asyncio, importlib.metadata, json, os, pathlib, subprocess, sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
root = pathlib.Path(sys.argv[1])
version = importlib.metadata.version('serena-agent')
if version != sys.argv[2] or sys.version_info[:2] != (3, 13):
    raise RuntimeError('Serena package or managed Python version mismatch')
executable = root / 'bin' / 'serena'
settings = dict(python=str(root / 'tools/serena-agent/bin/python'), uv=str(root / 'bin/uv'), pythonInstallDir=str(root / 'python'))
# Existing workspace uv caches may refer to a retained release's interpreter.
# Validate those precise immutable targets; never admit a shared directory or arbitrary state link.
interpreters = {str(pathlib.Path(settings['python']).resolve())}
for release in root.parent.glob('release-*'):
    previous_python = release / 'tools/serena-agent/bin/python'
    if release.is_symlink() or not previous_python.is_file():
        continue
    probe = subprocess.run([str(previous_python), '-I', '-B', '-c',
        'import importlib.metadata, json, sys; print(json.dumps({"serena":importlib.metadata.version("serena-agent"),"python":".".join(map(str,sys.version_info[:3]))}))'],
        capture_output=True, text=True, timeout=5)
    try:
        identity = json.loads(probe.stdout)
        if probe.returncode == 0 and identity['python'].startswith('3.13.') and release.name.startswith('release-' + identity['serena'] + '.'):
            resolved = previous_python.resolve()
            if resolved.is_relative_to(release / 'python'):
                interpreters.add(str(resolved))
    except (ValueError, KeyError, TypeError):
        pass
settings['pythonExecutables'] = sorted(interpreters)
workspace = root / 'probe-workspace'
workspace.mkdir()
(workspace / 'example.py').write_text('def managed_probe():\n    return 1\n')
preparation = os.environ['GESTALT_SERENA_PREPARE']
# Exercise the release's native configuration APIs and project storage relocation.
subprocess.run([sys.executable, '-c', preparation, str(workspace), str(executable), json.dumps(settings), '--help'],
    check=True, timeout=20, stdout=subprocess.DEVNULL)
if not (workspace / '.gestalt/serena/project.yml').is_file() or (workspace / '.serena').exists():
    raise RuntimeError('incompatible Serena workspace storage contract')
help_text = subprocess.check_output([str(executable), 'start-mcp-server', '--help'], timeout=15, text=True)
for option in ('--context', '--mode', '--project', '--enable-web-dashboard', '--enable-gui-log-window'):
    if option not in help_text:
        raise RuntimeError('incompatible Serena CLI: missing ' + option)
async def catalog():
    parameters = StdioServerParameters(command=sys.executable, args=['-c', preparation, str(workspace), str(executable),
        json.dumps(settings), 'start-mcp-server', '--context', 'codex', '--mode', 'editing', '--project', str(workspace),
        '--enable-web-dashboard', 'false', '--open-web-dashboard', 'false', '--enable-gui-log-window', 'false'], env=dict(os.environ))
    parameters = StdioServerParameters(command=os.environ['GESTALT_SERENA_NODE'],
        args=['-e',os.environ['GESTALT_SERENA_SUPERVISOR'],parameters.command,json.dumps(parameters.args)],env=parameters.env)
    async with stdio_client(parameters) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()
            # Persist MCP wire names; SDK 2 defaults to Python snake_case names.
            return [tool.model_dump(mode='json', by_alias=True, exclude_none=True) for tool in (await session.list_tools()).tools]
tools = asyncio.run(asyncio.wait_for(catalog(), timeout=30))
required = {'get_symbols_overview', 'find_symbol', 'initial_instructions', 'replace_symbol_body', 'insert_after_symbol', 'write_memory'}
if not required.issubset({tool['name'] for tool in tools}):
    raise RuntimeError('incomplete Serena Codex editing tool contract')
# Keep the venv Python path, not its symlink target: it selects installed packages.
descriptor = dict(schemaVersion=1, contractVersion=1, version=version, executable=str(executable),
    python=str(root / 'tools/serena-agent/bin/python'), uv=str(root / 'bin/uv'),
    pythonInstallDir=str(root / 'python'), pythonExecutables=settings['pythonExecutables'], tools=tools)
(root / 'active.json').write_text(json.dumps(descriptor) + '\n')
PYTHON
  mv -f -- "$candidate/active.json" "$gestalt_home/serena/active.json"
  # Keep candidate and old releases; a live session may still own the old executable.
  serena_install_candidate=''
  rm -rf -- "$candidate/probe" "$candidate/probe-workspace" "${candidate:?}/home" "$candidate/tmp" "$candidate/cache"
  rm -f -- "$candidate/uv.tar.gz" "$candidate/uv.sha256"
  log "installed Serena $version with uv $MANAGED_UV_VERSION and Python 3.13"
}

# Embedded to preserve the manager's single-file distribution contract.
playwright_runtime() {
  cat <<'PLAYWRIGHT_JS'
const fs = require('node:fs');
process.umask(0o077);
const path = require('node:path');
const {spawn, spawnSync} = require('node:child_process');
const {createHash} = require('node:crypto');
const [home, action = 'help', ...args] = process.argv.slice(1);
const root = path.join(home, 'playwright');
const stable = /^\d+\.\d+\.\d+$/;
const integrity = /^sha512-[A-Za-z0-9+/]{86}==$/;
const standard = new Set(['browser_navigate','browser_navigate_back','browser_snapshot','browser_click',
  'browser_hover','browser_drag','browser_select_option','browser_type','browser_press_key','browser_fill_form',
  'browser_take_screenshot','browser_wait_for','browser_handle_dialog','browser_file_upload',
  'browser_console_messages','browser_network_requests','browser_tabs','browser_close','browser_resize',
  'browser_run_code_unsafe','browser_evaluate']);
let stage, lock, child, browserScratchFd, browserProbe;
function browserEnvironment() {
  const env=runtimeEnv(),directory=env.TMPDIR||env.TMP||env.TEMP;
  // Chromium appends a random directory and SingletonSocket to TMPDIR. Keep
  // the same owned storage but shorten its name below Linux's sun_path limit.
  // The backend holds this descriptor until Chrome has finished shutting down.
  if(process.platform==='linux' && directory && Buffer.byteLength(directory)>50) {
    const canonical=fs.realpathSync(directory);
    browserScratchFd=fs.openSync(canonical,fs.constants.O_RDONLY|fs.constants.O_DIRECTORY|fs.constants.O_NOFOLLOW);
    const held=fs.fstatSync(browserScratchFd),current=fs.statSync(canonical);
    const alias='/proc/'+process.pid+'/fd/'+browserScratchFd;
    const target=fs.statSync(alias);
    if(!held.isDirectory() || process.getuid && held.uid!==process.getuid() ||
       held.dev!==current.dev || held.ino!==current.ino || target.dev!==held.dev || target.ino!==held.ino)
      fail('cannot establish browser temporary directory ownership');
    return {...env,TMPDIR:alias,TMP:alias,TEMP:alias};
  }
  return env;
}
function workspaceLayout(workspace) {
  const canonical=fs.realpathSync(workspace);
  if(!fs.statSync(canonical).isDirectory())fail('Playwright workspace must be a directory');
  const state=path.join(root,'workspaces',hash(canonical));
  return {workspace:canonical,state,userDataDir:path.join(state,'chrome'),lease:path.join(state,'lease')};
}
function alive(pid,group=false) {
  if(!Number.isSafeInteger(pid)||pid<2)return true;
  try{process.kill(group?-pid:pid,0);return true;}catch(e){return e.code!=='ESRCH';}
}
let sessionLease;
function releaseLease() {
  if(!sessionLease)return;
  try {const owner=json(path.join(sessionLease.lease,'owner.json'),8192);if(owner.token===sessionLease.token)fs.rmSync(sessionLease.lease,{recursive:true});}catch{}
  sessionLease=null;
}
function acquire(layout, ownership) {
  directory(layout.state);
  const recovering=path.join(layout.state,'recovering');
  safe(layout.lease);safe(recovering);
  const claim=()=>{
    if(fs.existsSync(recovering))fail('Playwright browser busy; chat remains available');
    try{fs.mkdirSync(layout.lease,{mode:0o700});return true;}catch(e){if(e.code!=='EEXIST')throw e;return false;}
  };
  if(!claim()) {
    // An absent process plus an absent process group is required. Unknown,
    // partial and live ownership records remain busy; Chromium locks stay intact.
    let old;try{old=json(path.join(layout.lease,'owner.json'),8192);}catch{fail('Playwright browser busy; incomplete ownership record');}
    if(old.schemaVersion!==1||old.workspace!==layout.workspace||!/^[a-f0-9]{48}$/.test(old.token||'')||
       typeof old.identity!=='string'||!old.identity||old.group!==old.pid||old.token!==ownership.staleToken)fail('Playwright browser busy; chat remains available');
    try{fs.mkdirSync(recovering,{mode:0o700});}catch{fail('Playwright browser busy; recovery in progress');}
    try {
      const current=json(path.join(layout.lease,'owner.json'),8192);
      if(current.token!==old.token)fail('Playwright browser busy; owner changed');
      fs.rmSync(layout.lease,{recursive:true});
      fs.mkdirSync(layout.lease,{mode:0o700});
    }finally{fs.rmdirSync(recovering);}
  }
  const token=require('node:crypto').randomBytes(24).toString('hex');
  sessionLease={...layout,token};
  const owner={schemaVersion:1,workspace:layout.workspace,pid:ownership.pid,identity:ownership.identity,group:ownership.group,token};
  if(!Number.isSafeInteger(owner.pid)||owner.pid<2||owner.group!==owner.pid||typeof owner.identity!=='string')fail('invalid browser process ownership');
  if(!owner.identity)fail('cannot establish browser process identity');
  fs.writeFileSync(path.join(layout.lease,'owner.json'),JSON.stringify(owner)+'\n',{mode:0o600,flag:'wx'});
  directory(layout.userDataDir);
}
async function backend(workspace,executablePath,ownership) {
  if(ownership.useProcessIdentity) {
    const identity=process.platform==='linux'?fs.readFileSync('/proc/self/stat','utf8').split(') ').at(-1).split(' ')[19]:
      spawnSync('ps',['-o','lstart=','-p',String(process.pid)],{encoding:'utf8',timeout:2000}).stdout.trim();
    ownership={...ownership,pid:process.pid,group:process.pid,identity};
  }
  const d=installed(),chrome=browser(executablePath);
  if(!chrome.ready)fail('Playwright Chrome unavailable; install Chrome outside Gestalt');
  const layout=workspaceLayout(workspace);acquire(layout,ownership);
  const config=path.join(layout.lease,'config.json'),browserEnv=browserEnvironment();
  fs.writeFileSync(config,JSON.stringify({browser:{browserName:'chromium',userDataDir:layout.userDataDir,
    launchOptions:{executablePath:chrome.executable,headless:true,chromiumSandbox:true,env:browserEnv}},
    capabilities:[],webmcp:false,outputDir:layout.state,codegen:'none'}),{mode:0o600});
  directory(path.join(layout.state,'config'));directory(path.join(layout.state,'cache'));
  await new Promise((resolve,reject)=>{
    // The host launcher owns this group, including Chrome descendants.
    child=spawn(process.execPath,[d.executable,'--config',config],{cwd:layout.workspace,env:{...runtimeEnv(),PWTEST_SOCKETS_DIR:browserEnv.TMPDIR,XDG_CONFIG_HOME:path.join(layout.state,'config'),XDG_CACHE_HOME:path.join(layout.state,'cache')},stdio:['pipe','pipe','pipe']});
    const upstream=child;
    let closing=false,terminating=false,closeTimer,killTimer,lines;
    const terminate=()=>{
      if(terminating)return;terminating=true;clearTimeout(closeTimer);
      upstream.kill('SIGTERM');killTimer=setTimeout(()=>upstream.kill('SIGKILL'),600);
    };
    const stop=()=>{
      if(closing)return;closing=true;
      // The client may kill its proxy before browser_close completes. Keep
      // this backend's upstream pipe alive and flush independently of it.
      process.stdin.unpipe(upstream.stdin);upstream.stdout.unpipe(process.stdout);
      const id='gestalt-managed-browser-close';
      lines=require('node:readline').createInterface({input:upstream.stdout});
      lines.on('line',line=>{try{if(JSON.parse(line).id===id)terminate();}catch{}});
      closeTimer=setTimeout(terminate,2000);
      upstream.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method:'tools/call',params:{name:'browser_close',arguments:{}}})+'\n');
    };
    upstream.stderr.resume();upstream.stdin.on('error',()=>{});
    upstream.stdout.pipe(process.stdout);process.stdin.pipe(upstream.stdin,{end:false});
    process.stdin.on('end',stop);process.stdout.on('error',stop);
    process.on('SIGTERM',stop);process.on('SIGINT',stop);
    upstream.on('error',reject);upstream.on('close',code=>{
      clearTimeout(closeTimer);clearTimeout(killTimer);lines?.close();child=null;
      closing||code===0?resolve():reject(Error('browser session exited'));
    });
  });
}
async function proxy(workspace,executablePath) {
  const d=installed(),layout=workspaceLayout(workspace);
  const {createInterface}=require('node:readline');
  let runtime,next=0,closed=false;
  const send=value=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...value})+'\n');
  const supervise=`const {spawn,spawnSync}=require('node:child_process'),fs=require('node:fs');
const identity=process.platform==='linux'?fs.readFileSync('/proc/self/stat','utf8').split(') ').at(-1).split(' ')[19]:spawnSync('ps',['-o','lstart=','-p',String(process.pid)],{encoding:'utf8',timeout:2000}).stdout.trim();
const args=JSON.parse(process.argv[2]);args.push(JSON.stringify({pid:process.pid,group:process.pid,identity,staleToken:process.argv[4]||null}));
const manager=fs.readFileSync(process.env.GESTALT_PLAYWRIGHT_MANAGER,'utf8');
const runtime=manager.split('// BEGIN SESSION SCRATCH RUNTIME\\n')[1].split('// END SESSION SCRATCH RUNTIME')[0];
const {scratchSpawnProgram}=new Function('require',runtime+'\\nreturn {scratchSpawnProgram};')(require);
const program=manager.split("cat <<'PLAYWRIGHT_JS'\\n")[1].split('\\nPLAYWRIGHT_JS\\n')[0];
const child=scratchSpawnProgram(program,args,{cwd:process.argv[3],env:process.env,stdio:[3,'inherit','inherit'],label:'gestalt-playwright-backend'});
let ending=false,finished=false,code=0,timer;
function finish(){if(finished)return;finished=true;ending=true;clearTimeout(timer);try{process.kill(-process.pid,'SIGTERM');}catch{}setTimeout(()=>{try{process.kill(-process.pid,'SIGKILL');}catch{}process.exit(code);},750);}
function stop(){if(ending)return;ending=true;child.kill('SIGTERM');timer=setTimeout(finish,3000);}
process.stdin.resume();process.stdin.on('end',stop);process.on('SIGTERM',stop);process.on('SIGINT',stop);
child.on('error',()=>process.exit(1));child.on('exit',value=>{if(!ending)code=value??1;finish();});`;
  async function stop() {
    const old=runtime;runtime=null;if(!old)return;
    // Backend owns persistent-context flushing even if this proxy is killed.
    // Guardian bounds cleanup of that backend and all its owned descendants.
    old.process.stdin.end();old.process.stdio[3].end();
    for(const waiter of old.pending.values())waiter.reject(Error('browser session stopped'));
    old.pending.clear();await old.exited;old.lines.close();
  }
  async function start() {
    if(runtime)return runtime;
    // The host launcher and its guardian share a process namespace. Only a
    // provably absent owner and process group authorize stale recovery.
    let staleToken;
    try {
      const owner=json(path.join(layout.lease,'owner.json'),8192);
      if(owner.schemaVersion!==1||owner.workspace!==layout.workspace||!/^[a-f0-9]{48}$/.test(owner.token||'')||
         typeof owner.identity!=='string'||!owner.identity||owner.group!==owner.pid||alive(owner.pid)||alive(owner.group,true))fail('Playwright browser busy; chat remains available');
      staleToken=owner.token;
    }catch(error){
      if(error.code!=='ENOENT')throw error;
      try{if(fs.existsSync(layout.lease))fail('Playwright browser busy; incomplete ownership record');}catch(error){throw error;}
    }
    const argv=[home,'__backend',layout.workspace,executablePath||''];
    const manager=process.env.GESTALT_PLAYWRIGHT_MANAGER;
    const source=fs.readFileSync(manager,'utf8').match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
    if(!source)fail('temporary lifecycle runtime missing');
    const scratch=new Function('require',source[1]+'\nreturn {scratchGuardianProgram,scratchSpawnProgram};')(require);
    const supervisor=scratch.scratchGuardianProgram(manager,'playwright-mcp',supervise)||supervise;
    const processChild=scratch.scratchSpawnProgram(supervisor,[process.execPath,JSON.stringify(argv),layout.workspace,staleToken||''],
      {cwd:layout.workspace,env:{...runtimeEnv(),GESTALT_PLAYWRIGHT_MANAGER:manager},detached:true,stdio:['pipe','pipe','pipe','pipe'],label:'gestalt-playwright-lifetime'});
    const pending=new Map(),lines=createInterface({input:processChild.stdout});
    const instance={process:processChild,pending,lines,exited:new Promise(resolve=>processChild.once('close',resolve))};
    runtime=instance;
    // Discard upstream/browser stderr (paths, proxy credentials, cookies). Only
    // fixed manager diagnostics are emitted outside the JSON-RPC protocol.
    let diagnostic='';
    processChild.stderr.on('data',b=>{diagnostic=(diagnostic+b).slice(-4096);});
    processChild.stdin.on('error',()=>{});processChild.stdio[3].on('error',()=>{});
    const failPending=()=>{
      const error=Error(diagnostic.includes('gestalt: Playwright browser busy')?'Playwright browser busy; workspace already in use; chat remains available':
        diagnostic.includes('gestalt: Playwright Chrome unavailable')?'Playwright Chrome unavailable; install Chrome outside Gestalt':'Playwright browser session unavailable; chat remains available');
      error.managed=true;for(const waiter of pending.values())waiter.reject(error);pending.clear();
    };
    processChild.on('error',failPending);processChild.on('exit',failPending);
    lines.on('line',line=>{
      let message;try{if(line.length>8*1024*1024)throw Error();message=JSON.parse(line);}catch{failPending();processChild.stdin.end();return;}
      const waiter=pending.get(message.id);if(!waiter)return;pending.delete(message.id);
      message.error?waiter.reject(Error('browser request failed')):waiter.resolve(message.result);
    });
    instance.request=(method,params,timeout=30000)=>new Promise((resolve,reject)=>{
      const id=++next,timer=setTimeout(()=>{pending.delete(id);reject(Error('browser request timed out'));processChild.stdin.end();},timeout);
      pending.set(id,{resolve:value=>{clearTimeout(timer);resolve(value);},reject:error=>{clearTimeout(timer);reject(error);}});
      processChild.stdio[3].write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');
    });
    await instance.request('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'gestalt-playwright',version:'1'}});
    processChild.stdio[3].write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
    return instance;
  }
  async function toolsFor(connection) {
    if(!connection.tools) {
      // Older installations cached a navigation-only catalog. Read the actual
      // connected package's schemas without reinstalling it or changing Chrome.
      const listed=await connection.request('tools/list',{});
      if(!Array.isArray(listed?.tools) || listed.nextCursor)fail('incompatible Playwright tool catalog');
      connection.tools=listed.tools.filter(tool=>standard.has(tool.name) && tool.inputSchema);
    }
    return connection.tools;
  }
  const input=createInterface({input:process.stdin,crlfDelay:Infinity});
  let work=Promise.resolve();
  input.on('line',line=>{work=work.then(async()=>{
    let message;
    try {
      if(line.length>1024*1024)fail('oversized Playwright request');
      message=JSON.parse(line);
      if(message.id===undefined)return;
      if(message.method==='initialize')send({id:message.id,result:{protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'gestalt-playwright',version:d.version},instructions:'Host-owned browser tools use client MCP tool approvals and host filesystem authority. Shell sandbox roots do not constrain this MCP. A listed tool does not grant permission to act.'}});
      else if(message.method==='ping')send({id:message.id,result:{}});
      else if(message.method==='tools/list')send({id:message.id,result:{tools:await toolsFor(await start())}});
      else if(message.method==='tools/call') {
        if(!standard.has(message.params?.name))fail('Playwright tool disabled by managed policy');
        const connection=await start();
        if(!(await toolsFor(connection)).some(tool=>tool.name===message.params.name))fail('Playwright tool unavailable in connected package');
        const result=await connection.request('tools/call',{name:message.params.name,arguments:message.params.arguments||{}});
        send({id:message.id,result});
      } else send({id:message.id,error:{code:-32601,message:'Unsupported managed Playwright method'}});
    }catch(error){
      if(message?.id!==undefined)send({id:message.id,error:{code:-32000,message:error.managed?error.message:'Playwright unavailable: browser busy, missing Chrome, or browser session failed; chat remains available'}});
      // A rejected tool does not disrupt an existing browser connection.
      if(!error.managed||!error.message.includes('tool disabled'))await stop();
    }
  });});
  const finish=async()=>{if(closed)return;closed=true;await stop();process.exit(0);};
  input.on('close',finish);process.on('SIGTERM',finish);process.on('SIGINT',finish);
  await new Promise(resolve=>input.once('close',resolve));
}

const fail = message => { const error = Error(message); error.managed = true; throw error; };
const hash = value => createHash('sha256').update(value).digest('hex');
function safe(p) {
  if (!path.isAbsolute(p) || path.normalize(p) !== p || /[\x00-\x1f\x7f]/.test(p)) fail('invalid managed path');
  let current = path.parse(p).root;
  for (const part of p.slice(current.length).split(path.sep)) {
    current = path.join(current, part);
    try { if (fs.lstatSync(current).isSymbolicLink()) fail('managed path traverses symbolic link'); }
    catch (e) { if (e.code !== 'ENOENT') throw e; }
  }
  return p;
}
function directory(p) {
  safe(p); fs.mkdirSync(p, {recursive:true, mode:0o700});
  const s = fs.statSync(p);
  if (!s.isDirectory() || (process.getuid && s.uid !== process.getuid())) fail('managed directory has another owner');
  fs.chmodSync(p, 0o700);
}
function json(p, max = 262144) {
  safe(p); const s = fs.statSync(p);
  if (!s.isFile() || s.size > max) fail('invalid or oversized metadata');
  return JSON.parse(fs.readFileSync(p, 'utf8'));
}
function installed() {
  const d = json(path.join(root, 'active.json'));
  if (d.schemaVersion !== 1 || d.contractVersion !== 1 || !stable.test(d.version) || !integrity.test(d.integrity) ||
      !/^>=20$/.test(d.node) || !Array.isArray(d.tools) || !d.tools.length || d.tools.some(n => !standard.has(n)) ||
      !Array.isArray(d.toolSchemas) || d.toolSchemas.length !== d.tools.length || d.toolSchemas.some(t => !d.tools.includes(t.name) || !t.inputSchema)) fail('invalid Playwright installation metadata');
  const release = safe(d.release);
  if (path.dirname(release) !== root || !path.basename(release).startsWith('release-' + d.version + '-')) fail('invalid release location');
  const executable = safe(path.join(release,'node_modules/@playwright/mcp/cli.js'));
  const pkg = json(path.join(release,'node_modules/@playwright/mcp/package.json'));
  const packageLock = path.join(release,'package-lock.json');
  const releaseLock = json(packageLock, 4*1024*1024);
  if (hash(fs.readFileSync(packageLock)) !== d.lockSha256 || pkg.version !== d.version ||
      releaseLock.packages?.['node_modules/@playwright/mcp']?.integrity !== d.integrity ||
      hash(fs.readFileSync(executable)) !== d.executableSha256) fail('Playwright release identity mismatch');
  return {...d, executable};
}
function browser(explicit) {
  if (explicit && (!path.isAbsolute(explicit) || /[\x00-\x1f\x7f]/.test(explicit))) return {ready:false,reason:'invalid-executable'};
  const paths = explicit ? [explicit] : process.platform === 'darwin' ?
    ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium'] :
    ['/opt/google/chrome/chrome','/usr/bin/google-chrome-stable','/usr/bin/google-chrome','/usr/bin/chromium','/usr/bin/chromium-browser'];
  for (const p of paths) {
    try {
      fs.accessSync(p, fs.constants.X_OK);
      const r = spawnSync(p,['--version'],{encoding:'utf8',timeout:3000,maxBuffer:8192});
      const match = r.stdout?.trim().match(/^(?:Google Chrome(?: for Testing)?|Chromium) (\d+)\.([\d.]+)(?:\s.*)?$/);
      if (r.status === 0 && match && Number(match[1]) >= 120) return {ready:true,executable:fs.realpathSync(p),version:match[1]+'.'+match[2]};
      if (explicit) return {ready:false,reason:'incompatible-chrome'};
    } catch {}
  }
  return {ready:false,reason:'chrome-missing'};
}
// Never forward upstream environment controls, Node injection, or npm hooks.
function runtimeEnv() {
  const env = {};
  for (const name of ['PATH','HOME','USER','LOGNAME','LANG','LC_ALL','TMPDIR','TMP','TEMP','GESTALT_SESSION_TMP_CONTEXT','SystemRoot']) if (process.env[name]) env[name] = process.env[name];
  return {...env, PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:'1'};
}
function stopChild() { if (child?.pid) { try {if(sessionLease)child.kill('SIGTERM');else process.kill(-child.pid,'SIGTERM');} catch {} } }
function cleanup() {
  releaseLease();
  if(browserScratchFd!==undefined){fs.closeSync(browserScratchFd);browserScratchFd=undefined;}
  if (stage) { try { const active = json(path.join(root,'active.json')); if (active.release === stage) stage = null; } catch {} }
  if (stage) fs.rmSync(stage,{recursive:true,force:true});
  if (lock) fs.rmdirSync(lock);
}
async function run(command, argv, options = {}) {
  return await new Promise((resolve,reject) => {
    child = spawn(command,argv,{env:runtimeEnv(),detached:true,stdio:['ignore','pipe','pipe'],...options});
    let stdout = '', bytes = 0;
    const timer = setTimeout(() => {stopChild(); reject(Error('package command timed out'));},120000);
    child.stdout.on('data',b => { bytes += b.length; if(bytes > 4*1024*1024) {stopChild(); reject(Error('oversized package output'));} else stdout += b; });
    // Package diagnostics may contain credentials. Report only bounded manager errors.
    child.stderr.resume();
    child.on('error',reject);
    child.on('exit',code => {clearTimeout(timer); child = null; code === 0 ? resolve(stdout) : reject(Error('package command failed; prior release preserved'));});
  });
}
async function catalog(executable) {
  return await new Promise((resolve,reject) => {
    child = spawn(process.execPath,[executable,'--headless','--no-webmcp'],{env:runtimeEnv(),detached:true,stdio:['pipe','pipe','pipe']});
    let buffer = '', bytes = 0, done = false;
    const finish = (error, tools) => {if(done)return;done=true;clearTimeout(timer);stopChild();error ? reject(error) : resolve(tools);};
    const timer = setTimeout(() => finish(Error('MCP catalog timed out')),15000);
    const send = value => child.stdin.write(JSON.stringify(value)+'\n');
    child.stderr.resume(); child.stdin.on('error',()=>{});
    child.on('error',e=>finish(e)); child.on('exit',()=>{child=null;if(!done)finish(Error('MCP catalog exited'));});
    child.stdout.on('data',b=>{
      bytes += b.length; if(bytes > 262144) return finish(Error('oversized MCP catalog'));
      buffer += b;
      while(buffer.includes('\n')) {
        const i=buffer.indexOf('\n'), line=buffer.slice(0,i);buffer=buffer.slice(i+1);
        let value; try {value=JSON.parse(line);} catch {return finish(Error('invalid MCP protocol'));}
        if(value.id===1) { if(value.error)return finish(Error('MCP initialize failed')); send({jsonrpc:'2.0',method:'notifications/initialized'});send({jsonrpc:'2.0',id:2,method:'tools/list'}); }
        if(value.id===2) {
          const tools=value.result?.tools;
          if(!Array.isArray(tools) || !['browser_navigate','browser_fill_form','browser_take_screenshot','browser_run_code_unsafe'].every(n=>tools.some(t=>t.name===n && t.inputSchema))) return finish(Error('incompatible upstream tools'));
          finish(null,tools.filter(t=>standard.has(t.name)).sort((a,b)=>a.name.localeCompare(b.name)));
        }
      }
    });
    send({jsonrpc:'2.0',id:1,method:'initialize',params:{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'gestalt-install-probe',version:'1'}}});
  });
}
async function install(version) {
  if (version && !stable.test(version)) fail('Playwright version must be stable major.minor.patch');
  if (Number(process.versions.node.split('.')[0]) < 20) fail('Playwright requires Node >=20');
  if (!['linux','darwin'].includes(process.platform)) fail('Playwright supports Linux and macOS');
  directory(root);
  lock = path.join(root,'.install-lock');
  try {fs.mkdirSync(lock,{mode:0o700});} catch {lock=null;fail('Playwright install already running; verify installer exited before removing stale .install-lock');}
  stage = fs.mkdtempSync(path.join(root,'release-'+(version || 'stable')+'-'));
  fs.writeFileSync(path.join(stage,'npmrc'),'',{mode:0o600});
  const npmEnv = {...runtimeEnv(),npm_config_cache:path.join(stage,'cache'),npm_config_userconfig:path.join(stage,'npmrc'),npm_config_globalconfig:'/dev/null',npm_config_registry:'https://registry.npmjs.org/',npm_config_engine_strict:'true',npm_config_ignore_scripts:'true',npm_config_update_notifier:'false'};
  const npm = argv => run('npm',argv,{cwd:stage,env:npmEnv});
  const release = JSON.parse(await npm(['view','@playwright/mcp@'+(version || 'latest'),'--json']));
  if (!stable.test(release.version) || (version && release.version !== version) || !integrity.test(release.dist?.integrity)) fail('invalid stable release metadata');
  version=release.version;
  // Use a version-bearing final location before generating lock metadata.
  const finalStage=path.join(root,'release-'+version+'-'+path.basename(stage).split('-').at(-1));
  if (finalStage !== stage) {fs.renameSync(stage,finalStage);stage=finalStage;npmEnv.npm_config_cache=path.join(stage,'cache');npmEnv.npm_config_userconfig=path.join(stage,'npmrc');}
  fs.writeFileSync(path.join(stage,'package.json'),JSON.stringify({private:true,dependencies:{'@playwright/mcp':version}}),{mode:0o600});
  await npm(['install','--package-lock-only','--ignore-scripts','--no-audit','--no-fund']);
  const packageLock=path.join(stage,'package-lock.json');
  const pinned=json(packageLock,4*1024*1024);
  if (pinned.packages?.['node_modules/@playwright/mcp']?.integrity !== release.dist.integrity) fail('package integrity mismatch');
  for (const [name,p] of Object.entries(pinned.packages || {})) if (name && (!/^https:\/\/registry\.npmjs\.org\//.test(p.resolved || '') || !integrity.test(p.integrity || ''))) fail('unverified dependency source');
  await npm(['ci','--ignore-scripts','--no-audit','--no-fund']);
  const executable=path.join(stage,'node_modules/@playwright/mcp/cli.js');
  const pkg=json(path.join(stage,'node_modules/@playwright/mcp/package.json'));
  if(pkg.version!==version) fail('package version mismatch');
  const help=await run(process.execPath,[executable,'--help']);
  for(const option of ['--headless','--user-data-dir','--executable-path','--no-webmcp']) if(!help.includes(option)) fail('incompatible upstream CLI');
  const toolSchemas=await catalog(executable),tools=toolSchemas.map(t=>t.name);
  const descriptor={schemaVersion:1,contractVersion:1,version,integrity:release.dist.integrity,node:'>=20',release:stage,
    lockSha256:hash(fs.readFileSync(packageLock)),executableSha256:hash(fs.readFileSync(executable)),tools,toolSchemas};
  fs.rmSync(path.join(stage,'cache'),{recursive:true,force:true});
  const staged=path.join(stage,'active.json');
  fs.writeFileSync(staged,JSON.stringify(descriptor)+'\n',{mode:0o600});
  fs.renameSync(staged,path.join(root,'active.json'));
  stage=null; console.error('gestalt: installed Playwright '+version+' (Chrome externally maintained)');
}
(async()=>{
  safe(root);
  if (['help','-h','--help'].includes(action)) { console.log('Usage: gestalt playwright install [VERSION] | update [VERSION] | version [--json] | doctor [--json] [--launch] [--cwd ROOT] [--executable-path PATH] | mcp --cwd ROOT [--executable-path PATH]\nInstall adds missing system Chrome on Debian amd64. Chrome is externally maintained; update, startup and doctor never download it. --launch tests a disposable local page.'); return; }
  if (['install','update'].includes(action)) {
    if(args.length>1)fail('usage: gestalt playwright '+action+' [VERSION]');
    if(action==='install' && !args.length) {try {installed(); console.error('gestalt: Playwright already installed and validated');return;}catch{}}
    await install(args[0] || (action === 'install' ? '0.0.83' : undefined));return;
  }
  if(action==='version') {
    if(args.length && !(args.length===1 && args[0]==='--json')) fail('usage: gestalt playwright version [--json]');
    const d=installed();console.log(args.length?JSON.stringify(d):'playwright '+d.version);return;
  }
  if(action==='doctor') {
    let explicit, workspace, output=false,launch=false;
    for(let i=0;i<args.length;i++) {if(args[i]==='--json')output=true;else if(args[i]==='--launch')launch=true;else if(args[i]==='--cwd' && args[i+1])workspace=args[++i];else if(args[i]==='--executable-path' && args[i+1])explicit=args[++i];else fail('usage: gestalt playwright doctor [--json] [--launch] [--executable-path PATH]');}
    let pkg;try {const d=installed();let engine;try{engine=json(path.join(d.release,'node_modules/playwright/package.json')).version;}catch{}pkg={ready:true,version:d.version,integrity:d.integrity,playwrightVersion:typeof engine==='string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(engine) && engine.length<=100?engine:null};}catch{pkg={ready:false,reason:'package-absent-or-invalid'};}
    const chrome=browser(explicit),node=Number(process.versions.node.split('.')[0])>=20;
    const result={schemaVersion:1,contractVersion:1,ready:pkg.ready&&chrome.ready&&node,package:pkg,chrome,node:{ready:node,version:process.versions.node},...(workspace?{workspace:workspaceLayout(workspace)}:{})};
    result.browserTest='not-run';
    if(launch && result.ready) {
      let scratch;
      try {
        const env=browserEnvironment();
        scratch=fs.mkdtempSync(path.join(env.TMPDIR||require('node:os').tmpdir(),'playwright-probe-'));
        const {chromium}=require(path.join(installed().release,'node_modules/playwright'));
        browserProbe=await chromium.launchPersistentContext(path.join(scratch,'profile'),{
          executablePath:chrome.executable,headless:true,chromiumSandbox:true,env,timeout:8000});
        const page=await browserProbe.newPage();
        await page.goto('data:text/html,<title>Gestalt browser check</title>',{timeout:3000});
        if(await page.title()!=='Gestalt browser check')throw Error('browser check failed');
        result.browserTest='passed';
      }catch{result.browserTest='failed';result.ready=false;}
      finally {
        try{if(browserProbe)await browserProbe.close();}catch{result.browserTest='failed';result.ready=false;}
        browserProbe=null;
        if(scratch)fs.rmSync(scratch,{recursive:true,force:true});
      }
    }
    console.log(output?JSON.stringify(result):'Playwright package: '+(pkg.version || pkg.reason)+'\nChrome: '+(chrome.version || chrome.reason)+'\nNode: '+(node?'ready':'requires >=20'));
    if(!result.ready)process.exitCode=1;return;
  }
  if(action==='mcp') {
    if(Number(process.versions.node.split('.')[0])<20)fail('Playwright requires Node >=20');
    let workspace,explicit;
    for(let i=0;i<args.length;i++) {if(args[i]==='--cwd'&&args[i+1])workspace=args[++i];else if(args[i]==='--executable-path'&&args[i+1])explicit=args[++i];else fail('usage: gestalt playwright mcp --cwd ROOT [--executable-path PATH]');}
    if(!workspace)fail('Playwright mcp requires --cwd ROOT');
    await proxy(workspace,explicit);return;
  }
  if(action==='__backend'&&args.length===3){if(Number(process.versions.node.split('.')[0])<20)fail('Playwright requires Node >=20');await backend(args[0],args[1]||undefined,JSON.parse(args[2]));return;}
  fail('unknown Playwright command');
})().catch(error=>{console.error('gestalt: '+(error.managed ? error.message : 'Playwright operation failed; invalid metadata or failed staging; prior release preserved'));process.exitCode=1;}).finally(()=>{try{cleanup();}catch{console.error('gestalt: Playwright cleanup incomplete; verify owned processes');process.exitCode=1;}});
let stopping=false;
function shutdown(code) {
  if(stopping)return;stopping=true;
  if(browserProbe){browserProbe.close().catch(()=>{}).finally(()=>{cleanup();process.exit(code);});return;}
  const pid=child?.pid;
  if(!pid){cleanup();process.exit(code);}
  const finish=()=>{clearTimeout(timer);cleanup();process.exit(code);};
  const timer=setTimeout(()=>{try{if(sessionLease)child.kill('SIGKILL');else process.kill(-pid,'SIGKILL');}catch{}finish();},600);
  child.once('exit',finish);stopChild();
}
// Stdio proxy/backend handlers own persistent-context and guardian teardown.
// Generic package shutdown must not preempt their asynchronous browser close.
if(!['mcp','__backend'].includes(action)) {
  process.on('SIGTERM',()=>shutdown(143));
  process.on('SIGINT',()=>shutdown(130));
}
PLAYWRIGHT_JS
}

playwright_chrome_binary() {
  local chrome
  for chrome in google-chrome google-chrome-stable chromium chromium-browser; do
    if command -v "$chrome" >/dev/null 2>&1; then
      command -v "$chrome"
      return 0
    fi
  done
  for chrome in '/opt/google/chrome/chrome' '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' '/Applications/Chromium.app/Contents/MacOS/Chromium'; do
    if [[ -x $chrome ]]; then printf '%s\n' "$chrome"; return 0; fi
  done
  return 1
}

playwright_debian_host() {
  local ID='' ID_LIKE=''
  [[ -r /etc/os-release ]] || return 1
  # Standard host-owned distribution metadata, not an operator-supplied file.
  # shellcheck source=/dev/null
  . /etc/os-release
  [[ $ID == debian || " $ID_LIKE " == *' debian '* ]]
}

install_playwright_chrome() (
  local chrome chrome_install_scratch='' architecture
  local -a privilege=()
  if chrome=$(playwright_chrome_binary); then
    log "system browser already available: $chrome"
    return 0
  fi
  if [[ $(uname -s) != Linux ]] || ! playwright_debian_host; then
    log 'Chrome is missing; install it separately on this operating system'
    return 0
  fi
  require_command dpkg
  architecture=$(dpkg --print-architecture)
  if [[ $architecture != amd64 ]]; then
    log "Chrome's Debian package requires amd64 (host: $architecture); install a supported browser separately"
    return 0
  fi
  require_command curl
  require_command apt-get
  if [[ $(id -u) != 0 ]]; then require_command sudo; privilege=(sudo); fi
  log 'installing missing Google Chrome system-wide from Google (sudo may prompt)'
  trap 'exit 130' INT
  trap 'exit 143' TERM
  trap '[[ -z $chrome_install_scratch ]] || rm -rf -- "$chrome_install_scratch"' EXIT
  chrome_install_scratch=$(mktemp -d "${TMPDIR:-/tmp}/gestalt-chrome.XXXXXXXX")
  if ! curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
    --connect-timeout 20 --max-time 300 \
    https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
    --output "$chrome_install_scratch/google-chrome-stable.deb"; then
    die 'Chrome download failed; rerun gestalt playwright install to retry'
  fi
  if ! "${privilege[@]}" apt-get install -y "$chrome_install_scratch/google-chrome-stable.deb"; then
    die 'Chrome system installation failed; rerun gestalt playwright install to retry'
  fi
  chrome=$(playwright_chrome_binary) || die 'Chrome installation completed but its binary was not found'
  "$chrome" --version || die 'installed Chrome could not report its version'
)

# Keep the single-file manager while passing embedded programs on a source pipe.
# fd 4 preserves the caller's stdin independently of Node's initial source read.
exec_node_program() {
  local program=$1
  shift
  exec node --input-type=commonjs - "$@" 4<&0 <<NODE
process.argv.splice(1, 1);
process[Symbol.for('gestalt.stdin.fd')] = 4;
{
  const fs = require('node:fs');
  Object.defineProperty(process,'stdin',{configurable:true,get(){
    const type=fs.fstatSync(4);
    const input=type.isFIFO()||type.isSocket()
      ? new (require('node:net').Socket)({fd:4,readable:true,writable:false})
      : fs.createReadStream(null,{fd:4});
    Object.defineProperty(process,'stdin',{value:input,configurable:true});
    return input;
  }});
}
$program
NODE
}

command_playwright() {
  [[ ${1:-} != __backend ]] || die 'internal Playwright command'
  require_command node
  if [[ ${1:-} == mcp ]]; then
    export GESTALT_PLAYWRIGHT_MANAGER="${BASH_SOURCE[0]}"
    exec_node_program "$(playwright_runtime)" "$gestalt_home" "$@"
  fi
  local playwright_pid result=0 saved_int saved_term
  saved_int=$(trap -p INT)
  saved_term=$(trap -p TERM)
  GESTALT_PLAYWRIGHT_MANAGER="${BASH_SOURCE[0]}" exec_node_program "$(playwright_runtime)" "$gestalt_home" "$@" <&0 &
  playwright_pid=$!
  trap 'kill -TERM "$playwright_pid" 2>/dev/null || true; wait "$playwright_pid" 2>/dev/null || true; exit 143' TERM
  trap 'kill -INT "$playwright_pid" 2>/dev/null || true; wait "$playwright_pid" 2>/dev/null || true; exit 130' INT
  wait "$playwright_pid" || result=$?
  trap - INT TERM
  if [[ -n $saved_int ]]; then eval "$saved_int"; fi
  if [[ -n $saved_term ]]; then eval "$saved_term"; fi
  if [[ $result == 0 && ${1:-} == install ]]; then install_playwright_chrome || return $?; fi
  return "$result"
}

command_serena() {
  local action=${1:-help}
  if (($#)); then shift; fi
  case $action in
    help | -h | --help)
      (($# == 0)) || die 'usage: gestalt serena help'
      cat <<'EOF'
Usage: gestalt serena <command> [options]

Commands:
  install                    Install private uv, Python 3.13 and tested Serena.
  update [VERSION]           Validate and activate a release; retain prior tooling.
  version                    Read the installed version without starting Serena.
  doctor [--cwd ROOT] [--json] Check installation and optional workspace readiness.
  index --cwd ROOT           Warm symbol and language caches for a project.
  mcp --cwd ROOT             Start the workspace MCP stdio connection.

Install once with 'gestalt serena install'. Codex and Mobile start the MCP
connection for selected workspaces when the Serena skill is enabled.
Use 'gestalt serena mcp --cwd /absolute/project/path' for an MCP client;
the command speaks JSON-RPC over stdin/stdout and runs until the client exits.
EOF
      ;;
    install)
      (($# == 0)) || die 'usage: gestalt serena install'
      if [[ -f $gestalt_home/serena/active.json ]] && serena_install_valid; then
        log 'Serena already installed and validated'
      else
        install_serena
      fi
      ;;
    update)
      (($# <= 1)) || die 'usage: gestalt serena update [VERSION]'
      local version=${1:-latest}
      if [[ $version == latest ]]; then
        require_command curl
        require_command node
        version=$(curl -q --fail --location --silent --show-error --proto '=https' --proto-redir '=https' \
          --connect-timeout 20 --max-time 30 https://pypi.org/pypi/serena-agent/json | \
          node -e 'let s=""; process.stdin.on("data",b=>s+=b); process.stdin.on("end",()=>{const d=JSON.parse(s);const versions=Object.keys(d.releases??{}).filter(v=>/^\d+\.\d+\.\d+$/.test(v)&&d.releases[v]?.some(f=>!f.yanked)).sort((a,b)=>{const x=a.split(".").map(Number),y=b.split(".").map(Number);return x[0]-y[0]||x[1]-y[1]||x[2]-y[2];});if(!versions.length)process.exit(1);process.stdout.write(versions.at(-1));});') ||
          die 'could not resolve the latest stable Serena release; prior installation preserved'
      fi
      install_serena "$version"
      ;;
    mcp)
      [[ $# == 2 && $1 == --cwd && -n $2 ]] || die 'usage: gestalt serena mcp --cwd ROOT; context, mode and project cannot be overridden'
      require_command node
      require_command codex
      [[ -d $2 ]] || die 'Serena workspace must be an existing directory'
      [[ -f $gestalt_home/serena/active.json ]] || die 'Serena is not installed; run gestalt serena install'
      GESTALT_SERENA_PREPARE="$(serena_workspace_prepare)" GESTALT_SERENA_WORKSPACE=$2 GESTALT_SERENA_INSTALL=$gestalt_home/serena/active.json run_serena_proxy
      ;;
    version | -V | --version)
      (($# == 0)) || die 'usage: gestalt serena version'
      local value
      value=$(serena_versions serena) || die 'Serena installation absent or invalid; run gestalt serena install'
      printf 'serena %s\n' "$value"
      ;;
    doctor | index)
      local workspace='' json_output=false
      while (($#)); do
        case $1 in
          --cwd) [[ $# -ge 2 && -d $2 ]] || die 'Serena --cwd requires an existing directory'; workspace=$2; shift 2 ;;
          --json) [[ $action == doctor ]] || die '--json is only supported for Serena doctor'; json_output=true; shift ;;
          *) die 'usage: gestalt serena doctor [--cwd ROOT] [--json] | index --cwd ROOT' ;;
        esac
      done
      [[ $action != index || -n $workspace ]] || die 'usage: gestalt serena index --cwd ROOT'
      serena_operator "$action" "$workspace" "$json_output"
      ;;
    *) die 'usage: gestalt serena install | update [VERSION] | version | doctor [--cwd ROOT] | index --cwd ROOT | mcp --cwd ROOT' ;;
  esac
}

serena_install_valid() {
  require_command node
  node - "$gestalt_home/serena/active.json" <<'JS'
const fs = require('node:fs'), {spawnSync} = require('node:child_process');
try {
  const d = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
  if (d.schemaVersion !== 1 || (d.contractVersion !== 1 && d.version !== '1.7.0') || !Array.isArray(d.tools) ||
      !['get_symbols_overview', 'find_symbol', 'replace_symbol_body'].every(n => d.tools.some(t => t.name === n && t.inputSchema))) process.exit(1);
  for (const p of [d.executable, d.python, d.uv]) fs.accessSync(p, fs.constants.X_OK);
  if (!fs.statSync(d.pythonInstallDir).isDirectory()) process.exit(1);
  const result = spawnSync(d.python, ['-I', '-B', '-c', 'import importlib.metadata; print(importlib.metadata.version("serena-agent"))'],
    {encoding: 'utf8', timeout: 5000});
  if (result.status !== 0 || result.stdout.trim() !== d.version) process.exit(1);
} catch { process.exit(1); }
JS
}

# Metadata reads never import Serena (its version flag initializes ~/.serena).
serena_versions() {
  command -v node >/dev/null 2>&1 || return 1
  node - "$gestalt_home/serena/active.json" "${1:-json}" <<'JS'
const fs = require('node:fs'), {spawnSync} = require('node:child_process');
try {
  const d = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
  if (d.schemaVersion !== 1 || (d.contractVersion !== 1 && d.version !== '1.7.0') || !/^\d+\.\d+\.\d+$/.test(d.version) ||
      !Array.isArray(d.tools) || !['find_symbol','get_symbols_overview','replace_symbol_body'].every(n => d.tools.some(t => t.name === n && t.inputSchema))) throw Error();
  for (const p of [d.python, d.executable, d.uv]) fs.accessSync(p, fs.constants.X_OK);
  if (!fs.statSync(d.pythonInstallDir).isDirectory()) throw Error();
  const py = spawnSync(d.python, ['-I', '-B', '-c',
    'import importlib.metadata, json, sys; print(json.dumps({"serena":importlib.metadata.version("serena-agent"),"python":".".join(map(str,sys.version_info[:3]))}))'],
    {encoding:'utf8',timeout:5000,maxBuffer:65536});
  const uv = spawnSync(d.uv,['--version'],{encoding:'utf8',timeout:5000,maxBuffer:65536});
  if (py.status !== 0 || uv.status !== 0) throw Error('metadata runtime failure');
  const value = JSON.parse(py.stdout), match = uv.stdout.trim().match(/^uv (\d+\.\d+\.\d+)(?:[ (]|$)/);
  if (value.serena !== d.version || !/^3\.13\.\d+$/.test(value.python) || !match) throw Error('metadata identity mismatch');
  value.uv = match[1];
  console.log(process.argv[3] === 'serena' ? value.serena : process.argv[3] === 'uv' ? value.uv : process.argv[3] === 'python' ? value.python : JSON.stringify(value));
} catch (error) { console.error('gestalt: Serena versions: ' + (error.message || 'invalid installation')); process.exit(1); }
JS
}

codex_sandbox_probe() {
  node --input-type=module - <<'JS'
import { readFile, realpath, mkdtemp, rm, access, stat } from 'node:fs/promises';
import { constants } from 'node:fs';
import { spawn, spawnSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { join, dirname, delimiter } from 'node:path';
const report = { ready: false, reason: 'codex-not-found', bubblewrap: null, userNamespaces: {} };
const executable = async path => { try { await access(path, constants.X_OK); return await realpath(path); } catch { return null; } };
const find = async name => {
  for (const directory of (process.env.PATH ?? '').split(delimiter)) {
    const path = await executable(join(directory || '.', name));
    if (path) return path;
  }
  return null;
};
let temporary, child, timer, signal;
try {
  const codex = await find('codex');
  if (process.platform === 'linux') {
    for (const name of ['kernel.unprivileged_userns_clone', 'kernel.apparmor_restrict_unprivileged_userns', 'user.max_user_namespaces']) {
      try { report.userNamespaces[name] = (await readFile('/proc/sys/' + name.replaceAll('.', '/'), 'utf8')).trim(); }
      catch { report.userNamespaces[name] = null; }
    }
    let bwrap = await find('bwrap'), source = 'system';
    if (!bwrap && codex) {
      const candidates = [join(dirname(codex), '../codex-resources/bwrap'), join(dirname(codex), 'codex-resources/bwrap')];
      if (['x64', 'arm64'].includes(process.arch)) {
        const triple = (process.arch === 'x64' ? 'x86_64' : 'aarch64') + '-unknown-linux-musl';
        try {
          const packagePath = createRequire(codex).resolve('@openai/codex-linux-' + process.arch + '/package.json');
          candidates.push(join(dirname(packagePath), 'vendor', triple, 'codex-resources/bwrap'));
        } catch {}
        candidates.push(join(dirname(codex), '../vendor', triple, 'codex-resources/bwrap'));
      }
      for (const candidate of candidates) { bwrap = await executable(candidate); if (bwrap) break; }
      source = 'bundled';
    }
    if (bwrap) {
      const version = spawnSync(bwrap, ['--version'], { encoding: 'utf8', timeout: 1000, maxBuffer: 4096 });
      report.bubblewrap = { available: version.status === 0, path: bwrap, source, version: version.status === 0 ? version.stdout.trim() : null };
    } else report.bubblewrap = { available: false, path: null, source: null, version: null };
  }
  if (codex) {
    temporary = await mkdtemp(join(tmpdir(), 'gestalt-sandbox-doctor-'));
    let stderr = '', timedOut = false;
    child = spawn(codex, ['-c', 'default_permissions=":read-only"', 'sandbox', '--', '/bin/true'],
      { detached: true, env: { ...process.env, CODEX_HOME: temporary }, stdio: ['ignore', 'ignore', 'pipe'] });
    const kill = kind => { if (child?.pid) { try { process.kill(-child.pid, kind); } catch {} } };
    signal = () => kill('SIGKILL');
    process.on('SIGINT', signal); process.on('SIGTERM', signal);
    child.stderr.on('data', data => { stderr = (stderr + data).slice(-4096); });
    timer = setTimeout(() => { timedOut = true; kill('SIGKILL'); }, 5000);
    const result = await new Promise(resolve => {
      child.once('error', error => resolve({ error })); child.once('close', code => resolve({ code }));
    });
    clearTimeout(timer); kill('SIGKILL');
    report.ready = result.code === 0 && !timedOut;
    report.reason = timedOut ? 'sandbox-timeout' : report.ready ? 'ready' : 'sandbox-startup-failed';
    if (!report.ready) report.diagnostic = (stderr.trim() || result.error?.message || 'Codex sandbox exited with code ' + result.code).slice(-4096);
    if (!report.ready && process.platform === 'linux' &&
        report.diagnostic?.includes('app-server socket directory must be a user-owned directory with mode 0700')) {
      const daemon = join(await realpath('/tmp'), 'codex-daemon-' + process.getuid());
      const info = await stat(daemon).catch(() => null);
      if (info?.isDirectory() && info.uid === process.getuid() && (info.mode & 0o777) === 0) {
        report.reason = 'sandbox-check-unavailable';
        report.diagnostic = 'The current sandbox masks the Codex daemon directory. Run gestalt doctor from a host shell; this nested check cannot establish host sandbox health.';
      }
    }
  }
} catch (error) { report.reason = 'sandbox-probe-failed'; report.diagnostic = error.message; }
finally {
  clearTimeout(timer);
  if (signal) { process.off('SIGINT', signal); process.off('SIGTERM', signal); }
  if (temporary) await rm(temporary, { recursive: true, force: true });
}
console.log(JSON.stringify(report));
JS
}

command_sandbox_doctor() {
  require_command node
  doctor_sandbox_report=$(codex_sandbox_probe)
  node --input-type=module - "$doctor_sandbox_report" <<'JS'
const report = JSON.parse(process.argv[2]);
if (report.bubblewrap) {
  console.log('Bubblewrap'.padEnd(24) + (report.bubblewrap.available
    ? report.bubblewrap.version + ' (' + report.bubblewrap.source + ')'
    : 'not found or unusable; check the Codex installation'));
}
for (const [name, value] of Object.entries(report.userNamespaces)) console.log(name + ' = ' + (value ?? 'unavailable'));
console.log('Codex sandbox'.padEnd(24) + (report.ready ? 'ready' : report.reason));
if (!report.ready) {
  if (report.diagnostic) console.log(report.diagnostic);
  if (report.reason !== 'sandbox-check-unavailable')
    console.log('Check Bubblewrap and unprivileged user namespaces, including Ubuntu AppArmor restrictions.');
}
process.exitCode = report.ready ? 0 : 1;
JS
}

serena_operator() {
  local action=$1 workspace=$2 json_output=$3 sandbox_report=''
  require_command node
  if [[ $action == doctor ]]; then
    sandbox_report=${doctor_sandbox_report:-$(codex_sandbox_probe)}
  fi
  GESTALT_SERENA_SANDBOX_REPORT=$sandbox_report \
    GESTALT_SERENA_PREPARE="$(serena_workspace_prepare)" GESTALT_SERENA_NODE="$(command -v node)" \
    GESTALT_SERENA_SUPERVISOR="$(serena_operator_supervisor)" \
    node --input-type=module - "$gestalt_home/serena/active.json" "$action" "$workspace" "$json_output" <<'JS'
import { readFile, realpath, mkdtemp, mkdir, rm, access, stat } from 'node:fs/promises';
import { constants } from 'node:fs';
import { spawn, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const [descriptor, action, directory, jsonOutput] = process.argv.slice(2);
const sandbox = action === 'doctor' ? JSON.parse(process.env.GESTALT_SERENA_SANDBOX_REPORT) : null;
let report = {installed:false,connected:false,projectReady:null,reason:'not-installed', ...(sandbox ? { sandbox } : {})};
let temporary, child, timer, signal, output = '', stderr = '', code = 1, timedOut=false;
const budget = Number(process.env.GESTALT_SERENA_DOCTOR_TIMEOUT_MS ?? 30000);
if (!Number.isInteger(budget) || budget < 100 || budget > 60000) throw Error('Serena doctor timeout must be 100..60000 ms');
const emit = () => {
  if (jsonOutput === 'true') console.log(JSON.stringify(report));
  else {
    console.log('Serena installed'.padEnd(24) + (report.installed ? 'yes' : 'no'));
    console.log('Serena sandbox'.padEnd(24) + (report.sandbox?.ready ? 'ready' : report.sandbox?.reason ?? 'not checked'));
    if (report.sandbox?.diagnostic) console.log(report.sandbox.diagnostic);
    console.log('Serena connected'.padEnd(24) + (report.connected ? 'yes' : 'no'));
    console.log('Serena project-ready'.padEnd(24) + (report.projectReady === null ? 'not checked (use --cwd ROOT)' : report.projectReady ? 'yes' : 'no'));
    console.log('Serena status'.padEnd(24) + report.reason);
    if (report.reason !== 'ready' && report.reason !== 'connected') console.log('Check gestalt serena install, language dependencies and the active filesystem/network permissions.');
  }
};
function killGroup(kind) { if (child?.pid) { try { process.kill(-child.pid, kind); } catch {} } }
const driver = String.raw`
import asyncio, json, os, pathlib, sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
settings = json.loads(sys.argv[1])
root = pathlib.Path(sys.argv[2]) if sys.argv[2] else None
scratch = pathlib.Path(sys.argv[3])
report = dict(installed=True, connected=False, projectReady=False if root else None, reason='connection-failed')
def publish():
    print(json.dumps(report), flush=True)
# Select one bounded, regular source file. Never follow project symlinks or inspect state.
extensions = {'.py','.js','.jsx','.ts','.tsx','.go','.rs','.c','.cpp','.cc','.h','.hpp','.java','.cs','.rb','.php','.swift','.kt','.kts','.scala','.ex','.exs','.clj','.dart','.lua','.sh'}
target = None
if root:
    visited = 0
    for directory, dirs, files in os.walk(root, followlinks=False):
        visited += 1
        dirs[:] = sorted(d for d in dirs if d not in {'.git','.gestalt','.serena','node_modules','.venv','venv','vendor','target','dist','build'} and not (pathlib.Path(directory)/d).is_symlink())
        for name in sorted(files):
            if visited >= 1000:
                break
            visited += 1
            p = pathlib.Path(directory)/name
            if not p.is_symlink() and p.is_file() and p.suffix in extensions:
                target = p.relative_to(root).as_posix()
                break
        if target or visited >= 1000:
            break
args = ['start-mcp-server','--context','codex','--mode','editing','--enable-web-dashboard','false','--open-web-dashboard','false','--enable-gui-log-window','false']
environment = dict(os.environ)
environment.update(SERENA_HOME=str(scratch/'serena'),HOME=str(scratch/'home'),
    PYTHONDONTWRITEBYTECODE='1',UV_TOOL_DIR=str(scratch/'uv-tools'),UV_TOOL_BIN_DIR=str(scratch/'uv-bin'),
    UV_CACHE_DIR=str(scratch/'uv-cache'),UV_PYTHON_INSTALL_DIR=settings['pythonInstallDir'],UV_PYTHON_DOWNLOADS='never',
    XDG_CACHE_HOME=str(scratch/'cache'),XDG_CONFIG_HOME=str(scratch/'config'),XDG_DATA_HOME=str(scratch/'data'),
    PATH=str(pathlib.Path(settings['uv']).parent)+os.pathsep+os.environ.get('PATH',''))
if 'GESTALT_SESSION_TMP_CONTEXT' not in environment:
    environment.update(TMPDIR=str(scratch),TMP=str(scratch),TEMP=str(scratch))
if target:
    parameters = StdioServerParameters(command=settings['python'], args=['-c',os.environ['GESTALT_SERENA_PREPARE'],
        str(root),settings['executable'],json.dumps(settings),*args,'--project',str(root)],env=environment)
else:
    # Projectless probes bypass workspace preparation, including its Serena 2
    # interface override. Select the same catalog without passing new options
    # to legacy releases that have no interface selection.
    from serena.config.serena_config import SerenaConfig
    if hasattr(SerenaConfig, 'agent_interface'):
        args += ['--agent-interface','tools']
    parameters = StdioServerParameters(command=settings['executable'],args=args,env=environment)
parameters = StdioServerParameters(command=os.environ['GESTALT_SERENA_NODE'],
    args=['-e',os.environ['GESTALT_SERENA_SUPERVISOR'],parameters.command,json.dumps(parameters.args)],env=parameters.env)
async def check():
    async with stdio_client(parameters) as (reader,writer):
        async with ClientSession(reader,writer) as session:
            await session.initialize()
            live = {t.name:t.model_dump(mode='json',by_alias=True,exclude_none=True) for t in (await session.list_tools()).tools}
            for tool in settings['tools']:
                if tool['name'] not in live or tool['inputSchema'] != live[tool['name']]['inputSchema']:
                    raise RuntimeError('installed catalog differs from native tools')
            report.update(connected=True,reason='connected')
            publish()
            if root and not target:
                report.update(projectReady=False,reason='no-supported-source-within-probe-limit')
            elif target:
                report.update(reason='language-service-failed')
                publish()
                result = await session.call_tool('get_symbols_overview',arguments={'relative_path':target})
                texts = [c.text for c in result.content if getattr(c,'type',None)=='text']
                # A real structured result proves this file's service; an error string or empty transport does not.
                payload = None
                for text in texts:
                    try:
                        value = json.loads(text)
                        if isinstance(value,(dict,list)):
                            payload = value
                    except (ValueError,TypeError):
                        pass
                if not result.isError and payload is not None and not (isinstance(payload,dict) and 'error' in payload):
                    report.update(projectReady=True,reason='ready')
try:
    asyncio.run(asyncio.wait_for(check(),timeout=float(sys.argv[4])/1000))
except TimeoutError:
    report['reason'] = 'language-service-timeout' if report['connected'] else 'connection-timeout'
except Exception as error:
    sys.stderr.write('gestalt: Serena doctor: '+str(error)+'\n')
publish()
sys.exit(0 if report['connected'] and report['projectReady'] is not False else 1)
`;
try {
  let install;
  try { install = JSON.parse(await readFile(descriptor,'utf8')); }
  catch (error) { report.reason = error.code === 'ENOENT' ? 'not-installed' : 'invalid-installation'; throw Error(report.reason); }
  report.reason = 'invalid-installation';
  if (install.schemaVersion !== 1 || (install.contractVersion !== 1 && install.version !== '1.7.0') || !Array.isArray(install.tools) ||
      !['find_symbol','get_symbols_overview','replace_symbol_body'].every(n=>install.tools.some(t=>t.name===n&&t.inputSchema))) throw Error(report.reason);
  for (const p of [install.python,install.executable,install.uv]) await access(p,constants.X_OK);
  if (!(await stat(install.pythonInstallDir)).isDirectory()) throw Error(report.reason);
  const metadata = spawnSync(install.python,['-I','-B','-c','import importlib.metadata, json, sys; print(json.dumps({"serena":importlib.metadata.version("serena-agent"),"python":".".join(map(str,sys.version_info[:3]))}))'],
    {encoding:'utf8',timeout:5000,maxBuffer:65536});
  const uv=spawnSync(install.uv,['--version'],{encoding:'utf8',timeout:5000,maxBuffer:65536});
  if(metadata.status!==0 || uv.status!==0)throw Error(report.reason);
  const identity=JSON.parse(metadata.stdout);
  if(identity.serena!==install.version || !/^3\.13\.\d+$/.test(identity.python) || !/^uv \d+\.\d+\.\d+(?:[ (]|$)/.test(uv.stdout.trim()))throw Error(report.reason);
  report.installed = true;
  if (sandbox && !sandbox.ready) { report.reason = 'sandbox-unavailable'; throw Error(report.reason); }
  const workspace = directory ? await realpath(directory) : '';
  report.projectReady = workspace ? false : null;
  report.reason = action === 'index' ? 'index-failed' : 'connection-failed';
  temporary = await mkdtemp(join(tmpdir(),'gestalt-serena-doctor-'));
  await mkdir(join(temporary,'home'));
  const argv = action === 'index' ? ['-B','-c',process.env.GESTALT_SERENA_PREPARE,workspace,install.executable,
    JSON.stringify(install),'project','index',workspace,'--timeout','10'] :
    ['-B','-c',driver,JSON.stringify(install),workspace,temporary,String(budget)];
  child = spawn(install.python,argv,{detached:true,stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONDONTWRITEBYTECODE:'1'}});
  child.stdout.on('data',b=>{ output += b; if (output.length > 1048576) killGroup('SIGTERM'); if(action==='index') process.stdout.write(b); });
  child.stderr.on('data',b=>{stderr=(stderr+b).slice(-8192); if(action==='index') process.stderr.write(b);});
  signal = () => killGroup('SIGTERM');
  process.on('SIGINT',signal);process.on('SIGTERM',signal);
  timer = setTimeout(()=>{ timedOut=true;report.reason='connection-timeout';killGroup('SIGTERM');setTimeout(()=>killGroup('SIGKILL'),750); },action==='index'?300000:budget+1000);
  code = await new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',v=>resolve(v??1));});
  clearTimeout(timer);
  killGroup('SIGTERM');
  // Leader exit alone does not prove native language descendants exited.
  await new Promise(resolve=>setTimeout(resolve,750));killGroup('SIGKILL');
  if(action==='doctor') {
    const lines=output.trim().split('\n');
    for(const line of lines) {try { const value=JSON.parse(line);if(typeof value.installed==='boolean')report={...value, ...(sandbox ? {sandbox} : {})};} catch {}}
    if(timedOut) report.reason=report.connected?'language-service-timeout':'connection-timeout';
    if(stderr && code !== 0) console.error(stderr.trim());
  }
} catch (error) { console.error('gestalt: Serena '+action+': '+error.message); }
finally {
  clearTimeout(timer);
  if(signal){process.off('SIGINT',signal);process.off('SIGTERM',signal);}
  killGroup('SIGKILL');
  if(temporary) await rm(temporary,{recursive:true,force:true});
}
if(action==='doctor'){if(!report.connected||report.projectReady===false)code=1;emit();}
process.exitCode=code;
JS
}

run_serena_proxy() {
  exec node --input-type=module - "${BASH_SOURCE[0]}" 3<&0 <<'NODE'
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { createReadStream } from 'node:fs';
import { readFile, realpath } from 'node:fs/promises';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const workspace = await realpath(process.env.GESTALT_SERENA_WORKSPACE);
const install = JSON.parse(await readFile(process.env.GESTALT_SERENA_INSTALL, 'utf8'));
const prepare = process.env.GESTALT_SERENA_PREPARE;
const allowed = new Set(['replace_in_files', 'replace_symbol_body', 'insert_after_symbol', 'insert_before_symbol',
  'search_for_pattern', 'get_symbols_overview', 'find_symbol', 'find_referencing_symbols', 'find_implementations',
  'find_declaration', 'get_diagnostics_for_file', 'rename_symbol', 'safe_delete_symbol', 'write_memory', 'read_memory',
  'list_memories', 'delete_memory', 'rename_memory', 'edit_memory', 'get_current_config', 'onboarding', 'initial_instructions']);
if (install.schemaVersion !== 1 || (install.contractVersion !== 1 && install.version !== '1.7.0') || typeof install.executable !== 'string' || typeof install.python !== 'string' ||
    typeof install.uv !== 'string' || typeof install.pythonInstallDir !== 'string' ||
    !Array.isArray(install.tools) || !install.tools.length || install.tools.some(t => !t?.name || !t.inputSchema))
  throw new Error('incompatible Serena installation; run gestalt serena install');
const tools = install.tools.filter(t => allowed.has(t.name));
if (!['get_symbols_overview', 'find_symbol', 'initial_instructions', 'replace_symbol_body'].every(name => tools.some(t => t.name === name)))
  throw new Error('incomplete Serena tool catalog; run gestalt serena install');
const guidance = 'Serena is bound to the active workspace. Follow the session instructions and approvals; '
  + 'collaboration plan mode prohibits edits even when the native filesystem policy permits them. '
  + 'A listed tool does not grant write authority. Do not switch projects or modes.';
const send = message => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
let runtime;
let closed = false;
let nextId = 0;
const budget = 30000;
// The supervisor owns a lifetime pipe separate from MCP stdin. Its EOF survives
// even an uncatchable proxy/owner exit and reaps the complete native process group.
const supervise = `
const {spawn}=require('node:child_process');
const child=spawn(process.argv[1],JSON.parse(process.argv[2]),{cwd:process.argv[3],env:process.env,stdio:[3,'inherit','inherit']});
let ending=false,exitCode=0;
function stop(){if(ending)return;ending=true;try{process.kill(-process.pid,'SIGTERM');}catch{}setTimeout(()=>{try{process.kill(-process.pid,'SIGKILL');}catch{}process.exit(exitCode);},750);}
process.stdin.resume();process.stdin.on('end',stop);process.on('SIGTERM',stop);process.on('SIGINT',stop);
// Leader exit does not prove descendant exit: retain the bounded escalation.
child.on('error',()=>{exitCode=1;stop();});child.on('exit',code=>{if(!ending)exitCode=code??1;stop();});
`;
async function stop() {
  const old = runtime;
  runtime = undefined;
  if (!old) return;
  old.child.stdin.end();
  old.child.stdio[3].end();
  for (const waiter of old.pending.values()) waiter.reject(new Error('Serena process stopped'));
  old.pending.clear();
  await old.exited;
  old.lines.close();
}
function policy(message) {
  const state = message.params?._meta?.['codex/sandbox-state-meta'];
  if (!state || state.permissionProfile?.type !== 'managed' ||
      state.permissionProfile.file_system?.type !== 'restricted' ||
      !Array.isArray(state.permissionProfile.file_system.entries) || typeof state.sandboxCwd !== 'string')
    throw new Error('Serena unavailable: supported effective Codex sandbox metadata required');
  // Accept only the native state for this bound workspace, never caller tool args.
  if (resolve(fileURLToPath(state.sandboxCwd)) !== workspace)
    throw new Error('Serena unavailable: Codex sandbox workspace differs from the bound project');
  return state;
}
async function start(state) {
  const key = JSON.stringify(state);
  if (runtime?.key === key && runtime.child.exitCode === null) return runtime;
  await stop();
  const args = ['sandbox', '--sandbox-state-json', key, '--', install.python, '-c', prepare, workspace, install.executable,
    JSON.stringify({ python: install.python, uv: install.uv, pythonInstallDir: install.pythonInstallDir, pythonExecutables: install.pythonExecutables ?? [] }),
    'start-mcp-server', '--project', workspace, '--context', 'codex', '--mode', 'editing',
    '--enable-web-dashboard', 'false', '--open-web-dashboard', 'false', '--enable-gui-log-window', 'false'];
  const manager = process.argv[2];
  const source = (await readFile(manager, 'utf8')).match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
  if (!source) throw Error('temporary lifecycle runtime missing');
  const {createRequire} = await import('node:module');
  const scratch = new Function('require', source[1] + '\nreturn {scratchGuardianProgram,scratchSpawnProgram};')(createRequire(import.meta.url));
  const supervisor = scratch.scratchGuardianProgram(manager, 'serena-mcp', supervise) ?? supervise;
  const child = scratch.scratchSpawnProgram(supervisor, ['codex', JSON.stringify(args), workspace],
    { cwd: workspace, env: process.env, detached: true, stdio: ['pipe', 'pipe', 'inherit', 'pipe'], label: 'gestalt-serena-lifetime' });
  const pending = new Map();
  const exited = new Promise(resolveExit => {
    child.once('close', resolveExit);
    child.once('error', resolveExit);
  });
  const lines = createInterface({ input: child.stdout });
  const instance = { key, child, pending, exited, lines };
  runtime = instance;
  const fail = () => { for (const waiter of pending.values()) waiter.reject(new Error('Serena native sandbox exited')); pending.clear(); };
  child.on('error', fail); child.on('exit', fail); child.stdio[3].on('error', fail); child.stdin.on('error', fail);
  lines.on('line', line => {
    let message;
    try { message = JSON.parse(line); } catch { fail(); child.stdin.end(); return; }
    const waiter = pending.get(message.id);
    if (!waiter) return;
    pending.delete(message.id);
    message.error ? waiter.reject(new Error('Serena MCP request failed')) : waiter.resolve(message.result);
  });
  instance.request = (method, params) => new Promise((resolveRequest, reject) => {
    const id = ++nextId;
    const timer = setTimeout(() => { pending.delete(id); reject(new Error('Serena MCP request timed out')); child.stdin.end(); }, budget);
    pending.set(id, { resolve: result => { clearTimeout(timer); resolveRequest(result); }, reject: error => { clearTimeout(timer); reject(error); } });
    child.stdio[3].write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
  });
  await instance.request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'gestalt-serena', version: '1' } });
  child.stdio[3].write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
  const live = await instance.request('tools/list', {});
  if (!tools.every(tool => live.tools?.some(t => t.name === tool.name && JSON.stringify(t.inputSchema) === JSON.stringify(tool.inputSchema)))) {
    await stop();
    throw new Error('Serena installed tool catalog does not match the running release');
  }
  return instance;
}
async function handle(message) {
  if (message.id === undefined) return;
  try {
    let result;
    if (message.method === 'initialize') result = { protocolVersion: message.params?.protocolVersion ?? '2024-11-05',
      capabilities: { tools: {}, experimental: { 'codex/sandbox-state-meta': {} } },
      serverInfo: { name: 'gestalt-serena', version: install.version }, instructions: guidance };
    else if (message.method === 'ping') result = {};
    else if (message.method === 'tools/list') result = { tools };
    else if (message.method === 'tools/call') {
      if (!tools.some(tool => tool.name === message.params?.name)) throw new Error('Serena tool unavailable in the bound Codex context');
      const state = policy(message);
      const instance = await start(state);
      result = await instance.request('tools/call', { name: message.params.name, arguments: message.params.arguments ?? {} });
      if (message.params.name === 'initial_instructions' && Array.isArray(result.content))
        result.content.push({ type: 'text', text: guidance });
    } else { send({ id: message.id, error: { code: -32601, message: 'Unsupported managed Serena MCP method' } }); return; }
    send({ id: message.id, result });
  } catch (error) {
    await stop();
    send({ id: message.id, error: { code: -32000, message: error.message } });
  }
}
const input = createInterface({ input: createReadStream(null, { fd: 3 }) });
let queue = Promise.resolve();
input.on('line', line => {
  let message;
  try { message = JSON.parse(line); } catch { send({ id: null, error: { code: -32700, message: 'Invalid JSON' } }); return; }
  queue = queue.then(() => closed ? undefined : handle(message));
});
async function close() { if (closed) return; closed = true; input.close(); await stop(); }
input.on('close', () => { void close(); });
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { void close(); });

NODE
}

require_command() {
  local -r command_name=$1
  command -v "$command_name" >/dev/null 2>&1 ||
    die "$command_name is required and was not found on PATH"
}

validate_managed_path() {
  local -r label=$1
  local -r candidate=$2
  local home_path

  [[ $candidate == /* ]] || die "$label must be an absolute path: $candidate"
  [[ $candidate != / ]] || die "refusing unsafe $label: /"
  home_path=$(CDPATH='' cd -- "${HOME:?HOME is required}" && pwd -P)
  [[ $candidate != "$home_path" ]] || die "refusing to use HOME itself as $label"
}

load_paths() {
  : "${HOME:?HOME is required}"
  codex_home=${CODEX_HOME:-$HOME/.codex-gestalt}
  gestalt_home=${GESTALT_HOME:-$HOME/.gestalt}
  install_base_url=${GESTALT_INSTALL_BASE_URL:-$DEFAULT_INSTALL_BASE_URL}
  marketplace=${GESTALT_MARKETPLACE:-$DEFAULT_MARKETPLACE}
  marketplace_name=${GESTALT_MARKETPLACE_NAME:-$DEFAULT_MARKETPLACE_NAME}
  mobile_version=${GESTALT_MOBILE_VERSION:-latest}
  mobile_root=$gestalt_home/mobile
  mobile_bin=$mobile_root/node_modules/.bin/gestalt-mobile
  user_skills_root=$HOME/.agents/skills
  managed_skills_root=$gestalt_home/.agents/skills
  codex_skills_root=$codex_home/skills
  skill_profiles_root=$gestalt_home/skill-profiles
  marketplace_setup=$codex_home/.tmp/marketplaces/$marketplace_name/gestalt-setup.sh
  agents_capability_manifest=$codex_home/.tmp/marketplaces/$marketplace_name/plugins/gestalt/gestalt-supervision-capabilities.json
  mobile_capability_manifest=$mobile_root/node_modules/gestalt-mobile/gestalt-supervision-capabilities.json

  validate_managed_path CODEX_HOME "$codex_home"
  validate_managed_path GESTALT_HOME "$gestalt_home"
  validate_managed_path 'user skills root' "$user_skills_root"
  validate_managed_path 'managed skills root' "$managed_skills_root"
  validate_managed_path 'Codex skills root' "$codex_skills_root"
  validate_managed_path 'skill profiles root' "$skill_profiles_root"
}

# Keep the transaction in this standalone wrapper: installed managers have no
# adjacent source modules. Package contents are data; never execute their tools.
command_skills() {
  local operation=${1:-help} output_mode=text
  if [[ $operation == help || $operation == --help || $operation == -h ||
        ( $# == 2 && ( $2 == --help || $2 == -h ) ) ]]; then
    printf '%s\n' 'Usage: gestalt skills install|update|status [--json]' \
      'Install/update maintain only the optional collection; choose activation in skill profiles.' \
      'Status reads current version, revision and integrity without changing files or downloading.'
    return
  fi
  case $operation in
    install | update) ;;
    status)
      if (($# == 2)) && [[ $2 == --json ]]; then output_mode=json;
      elif (($# != 1)); then die 'usage: gestalt skills status [--json]'; fi
      ;;
    *) die 'usage: gestalt skills install|update|status [--json]' ;;
  esac
  [[ $operation == status ]] || (($# == 1)) || die 'skills maintenance does not accept additional arguments'
  require_command node
  if [[ $operation != status ]]; then require_command git; fi
  node - "$operation" "$codex_home" "$DEFAULT_SKILLS_SOURCE" "$DEFAULT_SKILLS_REF" "$output_mode" <<'JS'
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { spawn } = require('node:child_process');
const [operation, selectedHome, canonicalSource, defaultRef, outputMode] = process.argv.slice(2);
const overridden = Object.hasOwn(process.env, 'GESTALT_SKILLS_SOURCE');
const source = overridden ? process.env.GESTALT_SKILLS_SOURCE : canonicalSource;
const ref = process.env.GESTALT_SKILLS_REF ?? defaultRef;
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
const fail = message => { throw new Error(message); };
const exists = file => { try { return fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } };
const json = file => JSON.parse(fs.readFileSync(file, 'utf8'));
let interrupted = false, child = null, home, root, discovery, lock, owner, stage;
let held = false, preserveRecovery = false;
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => {
  interrupted = true;
  if (child) child.kill('SIGTERM');
});
async function checkpoint() {
  await new Promise(resolve => setImmediate(resolve));
  if (interrupted) fail('skills maintenance interrupted; previous installation restored');
}
function plainDirectory(file) {
  const info = exists(file);
  if (info && (!info.isDirectory() || info.isSymbolicLink())) fail(`expected a directory without links: ${file}`);
  return info;
}
function plainFile(file) {
  const info = exists(file);
  if (!info?.isFile() || info.isSymbolicLink() || info.nlink !== 1) fail(`expected an ordinary package file: ${file}`);
}
function canonicalHome(file) {
  if (!path.isAbsolute(file) || file === '/' || path.normalize(file) !== file || /[\x00-\x1f\x7f]/.test(file)) fail('CODEX_HOME must be an absolute normalized directory');
  let ancestor = file, suffix = [];
  while (!exists(ancestor)) { suffix.unshift(path.basename(ancestor)); ancestor = path.dirname(ancestor); }
  if (!fs.statSync(ancestor).isDirectory()) fail('CODEX_HOME ancestor is not a directory');
  const resolved = path.join(fs.realpathSync(ancestor), ...suffix);
  if (resolved === '/' || resolved === fs.realpathSync(process.env.HOME)) fail('refusing resolved CODEX_HOME: root directory or HOME');
  return resolved;
}
function relativeFile(file) {
  return typeof file === 'string' && file.length <= 1024 && !/[\x00-\x1f\x7f\\]/.test(file)
    && !path.posix.isAbsolute(file) && file.split('/').every(p => p && p !== '.' && p !== '..');
}
function exactFields(value, fields) {
  if (!value || typeof value !== 'object' || Array.isArray(value)
      || !same(Object.keys(value).sort(), [...fields].sort())) fail(`invalid manifest object fields; expected ${fields.join(', ')}`);
}
function parseManifest(bytes) {
  // JSON.parse alone discards duplicate keys. Walk the already syntax-checked
  // document, comparing decoded keys in each object (including escaped aliases).
  const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
  const result = JSON.parse(text);
  let offset = 0;
  const space = () => { while (offset < text.length && /[\t\n\r ]/.test(text[offset])) offset++; };
  function string() {
    const start = offset++;
    while (text[offset] !== '"') { if (text[offset] === '\\') offset++; offset++; }
    return JSON.parse(text.slice(start, ++offset));
  }
  function value(depth) {
    if (depth > 64) fail('manifest nesting exceeds supported depth');
    space();
    if (text[offset] === '{') {
      offset++; space(); const keys = new Set();
      while (text[offset] !== '}') {
        const key = string();
        if (keys.has(key)) fail(`duplicate JSON key in manifest: ${key}`);
        keys.add(key); space(); offset++; space();
        const start = offset; value(depth + 1);
        if (depth === 0 && key === 'schemaVersion' && text.slice(start, offset) !== '1') fail('manifest schemaVersion must be integer 1');
        space();
        if (text[offset] !== ',') break;
        offset++; space();
      }
      offset++;
    } else if (text[offset] === '[') {
      offset++; space();
      while (text[offset] !== ']') { value(depth + 1); space(); if (text[offset] !== ',') break; offset++; }
      offset++;
    } else if (text[offset] === '"') string();
    else while (offset < text.length && !/[,\]}\s]/.test(text[offset])) offset++;
  }
  value(0);
  return result;
}
function validateManifest(manifest) {
  exactFields(manifest, ['schemaVersion', 'repository', 'source', 'version', 'skills']);
  if (manifest.schemaVersion !== 1 || manifest.repository !== 'dyne/gestalt-skills' || manifest.source !== canonicalSource
      || typeof manifest.version !== 'string' || !/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/.test(manifest.version)
      || !Array.isArray(manifest.skills) || !manifest.skills.length || manifest.skills.length > 256) fail('unsupported collection manifest');
  const names = new Set(), files = new Set();
  let previousName;
  for (const skill of manifest.skills) {
    exactFields(skill, ['name', 'entry', 'files']);
    if (typeof skill.name !== 'string' || skill.name.length >= 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill.name) || names.has(skill.name)
        || skill.entry !== `skills/${skill.name}/SKILL.md` || !Array.isArray(skill.files) || !skill.files.length) fail('invalid or duplicate skill in manifest');
    if (previousName !== undefined && previousName >= skill.name) fail('manifest skills must be sorted by name');
    names.add(skill.name); previousName = skill.name;
    let previousPath;
    for (const file of skill.files) {
      exactFields(file, ['path', 'sha256']);
      if (!relativeFile(file.path) || !file.path.startsWith(`skills/${skill.name}/`) || files.has(file.path)
          || typeof file.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(file.sha256)) fail('invalid, escaping or duplicate manifest file');
      if (previousPath !== undefined && previousPath >= file.path) fail('manifest files must be sorted by path');
      previousPath = file.path;
      files.add(file.path);
      if (files.size > 4096) fail('collection has too many files');
    }
    if (!skill.files.some(file => file.path === skill.entry)) fail('skill entry is absent from its file inventory');
  }
  return files;
}
function treeFiles(directory, prefix = '', directories = []) {
  plainDirectory(directory);
  const files = [];
  for (const name of fs.readdirSync(directory)) {
    const relative = prefix ? `${prefix}/${name}` : name;
    const file = path.join(directory, name), info = fs.lstatSync(file);
    if (info.isDirectory() && !info.isSymbolicLink()) {
      directories.push(relative); files.push(...treeFiles(file, relative, directories));
    }
    else { plainFile(file); files.push(relative); }
  }
  return files.sort();
}
function same(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
function inspectInstalled() {
  if (!plainDirectory(root)) return null;
  plainFile(path.join(root, 'manifest.json')); plainFile(path.join(root, 'receipt.json'));
  const manifestBytes = fs.readFileSync(path.join(root, 'manifest.json'));
  const manifest = parseManifest(manifestBytes), inventory = validateManifest(manifest);
  const receipt = json(path.join(root, 'receipt.json'));
  if (receipt?.schemaVersion !== 1 || receipt.repository !== manifest.repository || receipt.managedRoot !== root
      || receipt.discoveryRoot !== discovery || receipt.manifestSha256 !== hash(manifestBytes)
      || receipt.version !== manifest.version || !same(receipt.skills, manifest.skills)
      || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(receipt.revision)
      || typeof receipt.source !== 'string' || typeof receipt.verifiedSource !== 'boolean'
      || (receipt.verifiedSource && receipt.source !== canonicalSource)
      || !Array.isArray(receipt.packageFiles) || receipt.packageFiles.length !== 1
      || receipt.packageFiles[0].path !== 'LICENSE' || !/^[a-f0-9]{64}$/.test(receipt.packageFiles[0].sha256)) fail('collection receipt is missing, damaged or belongs to another installation; preserve it and inspect before retrying');
  const expected = ['LICENSE', 'manifest.json', 'receipt.json', ...inventory].sort();
  const directories = [], expectedDirectories = new Set();
  for (const file of inventory) {
    let parent = path.posix.dirname(file);
    while (parent !== '.') { expectedDirectories.add(parent); parent = path.posix.dirname(parent); }
  }
  if (!same(treeFiles(root, '', directories), expected) || !same(directories.sort(), [...expectedDirectories].sort())) fail('managed collection contains local or missing files; preserve local changes before updating');
  for (const file of [...manifest.skills.flatMap(skill => skill.files), ...receipt.packageFiles]) {
    if (hash(fs.readFileSync(path.join(root, file.path))) !== file.sha256) fail(`managed collection has local changes: ${file.path}; preserve them before updating`);
  }
  return { manifest, receipt };
}
function target(name) { return path.join(root, 'skills', name); }
function linkValue(name) {
  const file = path.join(discovery, name), info = exists(file);
  if (!info) return null;
  if (!info.isSymbolicLink()) fail(`skill collision: ${file}; move the unrelated entry before retrying`);
  return fs.readlinkSync(file);
}
function writeOwner() {
  const temp = path.join(lock, 'owner.tmp');
  fs.writeFileSync(temp, JSON.stringify(owner) + '\n', { mode: 0o600 });
  fs.renameSync(temp, path.join(lock, 'owner.json'));
}
function ownsCandidate() {
  try { return json(path.join(root, 'receipt.json')).transactionId === owner.token; } catch { return false; }
}
// The journal lives under the lock and precedes any visible mutation. Recovery
// handles process termination too; no stale PID is ever signalled or stolen.
function rollback() {
  if (!owner.journal) return;
  const backup = path.join(owner.stage, 'previous');
  if (exists(backup)) {
    if (exists(root)) {
      if (!ownsCandidate()) fail('recovery found unexpected collection content; preserved transaction for inspection');
      fs.rmSync(root, { recursive: true });
    }
    fs.renameSync(backup, root);
  } else if (!owner.journal.original && exists(root)) {
    if (!ownsCandidate()) fail('recovery found an unrelated collection; preserved transaction for inspection');
    fs.rmSync(root, { recursive: true });
  }
  for (const { name, before } of owner.journal.links) {
    const current = linkValue(name);
    if (current === before) continue;
    if (current !== null && current !== target(name)) fail(`recovery found a changed discovery entry: ${name}`);
    const file = path.join(discovery, name);
    if (current !== null) fs.unlinkSync(file);
    if (before !== null) fs.symlinkSync(before, file);
  }
}
function validateOwner(record) {
  if (record?.schemaVersion !== 1 || !Number.isSafeInteger(record.pid) || record.pid < 1
      || !/^[a-f0-9]{48}$/.test(record.token) || record.home !== home) fail('skills lock has unknown ownership; inspect .gestalt-skills.lock before retrying');
  if (record.stage !== null && (typeof record.stage !== 'string' || path.dirname(record.stage) !== home
      || !/^\.gestalt-skills-stage-[A-Za-z0-9]+$/.test(path.basename(record.stage)))) fail('skills recovery path is invalid');
  if (record.stage !== null) plainDirectory(record.stage);
  if (record.journal !== null && (!record.stage || typeof record.journal.original !== 'boolean'
      || typeof record.committed !== 'boolean' || !Array.isArray(record.journal.links)
      || record.journal.links.some(link => !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(link.name)
        || (link.before !== null && link.before !== target(link.name))))) fail('skills recovery journal is invalid');
}
function releaseLock() {
  const current = json(path.join(lock, 'owner.json'));
  if (current.token !== owner.token) fail('skills lock ownership changed; preserving recovery state');
  if (owner.stage) fs.rmSync(owner.stage, { recursive: true, force: true });
  fs.rmSync(lock, { recursive: true });
  held = false;
}
function acquireLock() {
  try { fs.mkdirSync(lock, { mode: 0o700 }); }
  catch (e) {
    if (e.code !== 'EEXIST') throw e;
    plainDirectory(lock); plainFile(path.join(lock, 'owner.json'));
    const previous = json(path.join(lock, 'owner.json'));
    validateOwner(previous);
    try { process.kill(previous.pid, 0); fail('another skills operation is running; retry when it finishes'); }
    catch (error) { if (error.code !== 'ESRCH') throw error; }
    // Claim recovery inside the existing lock. Rechecking its token prevents a
    // competing recovering process from removing a newly acquired lock.
    const claim = path.join(lock, 'recovery');
    fs.mkdirSync(claim, { mode: 0o700 });
    try {
      if (json(path.join(lock, 'owner.json')).token !== previous.token) fail('skills lock changed during recovery; retry');
      owner = previous;
      if (!owner.committed) rollback();
      releaseLock();
    } catch (error) { fs.rmdirSync(claim); throw error; }
    fs.mkdirSync(lock, { mode: 0o700 });
  }
  held = true;
  owner = { schemaVersion: 1, pid: process.pid, token: crypto.randomBytes(24).toString('hex'), home, stage: null, journal: null, committed: false };
  writeOwner();
}
function loadCollectionPaths() {
  home = canonicalHome(selectedHome);
  root = path.join(home, 'gestalt-skills'); discovery = path.join(home, 'skills'); lock = path.join(home, '.gestalt-skills.lock');
  plainDirectory(root); plainDirectory(discovery);
}
function status() {
  const report = { schemaVersion: 1, status: 'missing', integrity: 'missing', version: null, revision: null,
    managedRoot: null, discoveryRoot: null, verifiedSource: false, recoveryCommand: 'gestalt skills install' };
  try {
    loadCollectionPaths(); report.managedRoot = root; report.discoveryRoot = discovery;
    if (exists(root)) {
      plainFile(path.join(root, 'receipt.json'));
      const header = json(path.join(root, 'receipt.json'));
      if (typeof header.version === 'string' && header.version.length < 128 && /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/.test(header.version)) report.version = header.version;
      if (typeof header.revision === 'string' && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(header.revision)) report.revision = header.revision;
    }
    const installed = inspectInstalled();
    if (installed) {
      report.version = installed.receipt.version; report.revision = installed.receipt.revision;
      report.verifiedSource = installed.receipt.verifiedSource;
      for (const { name } of installed.manifest.skills) if (linkValue(name) !== target(name)) fail(`missing or changed discovery link: ${name}`);
      report.status = 'ready'; report.integrity = 'ok'; report.recoveryCommand = null;
    }
    if (exists(lock)) {
      report.status = 'recovery-required'; report.recoveryCommand = 'gestalt skills update';
      plainDirectory(lock); plainFile(path.join(lock, 'owner.json'));
      const record = json(path.join(lock, 'owner.json')); validateOwner(record);
      try { process.kill(record.pid, 0); report.status = 'busy'; }
      catch (error) { if (error.code !== 'ESRCH') throw error; }
      report.reason = report.status === 'busy' ? 'another skills operation is running; retry when it finishes' : 'interrupted maintenance; retry to recover';
    }
  } catch (error) {
    report.status = 'damaged'; report.integrity = 'invalid'; report.verifiedSource = false;
    report.recoveryCommand = 'gestalt skills update'; report.reason = error.message.slice(0, 512);
  }
  if (outputMode === 'json') console.log(JSON.stringify(report));
  else {
    console.log(`Gestalt skills           ${report.status.toUpperCase()}${report.version ? ` (${report.version}; ${report.revision})` : ''}`);
    console.log(`Skills integrity         ${report.integrity}${report.status === 'ready' && !report.verifiedSource ? ' (source override; unverified)' : ''}`);
    if (report.reason) console.log(`Skills detail            ${report.reason}`);
    if (report.recoveryCommand) console.log(`Skills recovery          ${report.recoveryCommand}${report.status === 'damaged' ? ' (preserve local changes and resolve the reported conflict first)' : ''}`);
  }
  if (report.status !== 'ready') process.exitCode = 1;
}
async function git(args, limit = 16 * 1024 * 1024) {
  await checkpoint();
  const env = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0' };
  for (const key of Object.keys(env)) if (/^GIT_/.test(key) && !['GIT_CONFIG_NOSYSTEM', 'GIT_CONFIG_GLOBAL', 'GIT_TERMINAL_PROMPT'].includes(key)) delete env[key];
  return await new Promise((resolve, reject) => {
    const buffers = []; let bytes = 0, problem;
    const proc = spawn('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'maintenance.auto=false', '-c', 'gc.auto=0', ...args], { env, stdio: ['ignore', 'pipe', 'ignore'] });
    child = proc;
    const timer = setTimeout(() => { problem = 'collection download exceeded 60 seconds'; proc.kill('SIGTERM'); }, 60000);
    const force = setTimeout(() => proc.kill('SIGKILL'), 65000);
    proc.stdout.on('data', data => { bytes += data.length; if (bytes > limit) { problem = 'collection data exceeds supported size'; proc.kill('SIGTERM'); } else buffers.push(data); });
    proc.on('error', error => { problem = `git unavailable: ${error.code}`; });
    proc.on('close', code => {
      clearTimeout(timer); clearTimeout(force); child = null;
      if (problem || code !== 0 || interrupted) reject(new Error(problem || (interrupted ? 'skills maintenance interrupted' : 'could not retrieve collection; check GESTALT_SKILLS_SOURCE and GESTALT_SKILLS_REF')));
      else resolve(Buffer.concat(buffers));
    });
  });
}
async function install() {
  if (typeof source !== 'string' || !source || /[\x00-\x1f\x7f]/.test(source)) fail('invalid collection source');
  if (!path.isAbsolute(source)) {
    let url; try { url = new URL(source); } catch { fail('collection source must be HTTPS or an absolute local test repository'); }
    if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) fail('collection source must be HTTPS without credentials, query or fragment');
  }
  if (typeof ref !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref) || ref.includes('..')) fail('invalid collection revision or ref');
  loadCollectionPaths();
  fs.mkdirSync(home, { recursive: true });
  acquireLock();
  try {
    const previous = inspectInstalled();
    stage = fs.mkdtempSync(path.join(home, '.gestalt-skills-stage-'));
    fs.chmodSync(stage, 0o700); owner.stage = stage; writeOwner();
    const repository = path.join(stage, 'repository'), candidate = path.join(stage, 'candidate');
    await git(['init', '--bare', '--template=', repository]);
    const inRepo = args => ['--git-dir', repository, ...args];
    await git(inRepo(['-c', 'protocol.file.allow=always', 'fetch', '--depth=1', '--no-tags', '--no-recurse-submodules', '--', source, ref]));
    const revision = (await git(inRepo(['rev-parse', '--verify', 'FETCH_HEAD^{commit}']))).toString().trim();
    if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(revision)) fail('download did not resolve to an immutable revision');
    const tree = (await git(inRepo(['ls-tree', '-r', '-z', revision]))).toString('utf8').split('\0').filter(Boolean);
    const blobs = new Map();
    for (const entry of tree) {
      const match = /^(100644|100755) blob ([a-f0-9]+)\t(.+)$/.exec(entry);
      if (!match) {
        const name = entry.slice(entry.indexOf('\t') + 1);
        if (name === 'manifest.json' || name === 'LICENSE' || name.startsWith('skills/')) fail('collection contains a symbolic link or unsupported file');
        continue;
      }
      blobs.set(match[3], { oid: match[2], mode: match[1] });
    }
    async function blob(name) {
      if (!blobs.has(name)) fail(`package is missing ${name}`);
      return await git(inRepo(['cat-file', 'blob', blobs.get(name).oid]), 4 * 1024 * 1024);
    }
    const manifestBytes = await blob('manifest.json');
    const manifest = parseManifest(manifestBytes), inventory = validateManifest(manifest);
    if (!same([...blobs.keys()].filter(name => name.startsWith('skills/')).sort(), [...inventory].sort())) fail('manifest does not cover every bundled skill file');
    fs.mkdirSync(candidate);
    let totalBytes = 0;
    for (const file of manifest.skills.flatMap(skill => skill.files)) {
      const bytes = await blob(file.path);
      if (hash(bytes) !== file.sha256) fail(`package digest mismatch: ${file.path}`);
      totalBytes += bytes.length;
      if (totalBytes > 64 * 1024 * 1024) fail('collection payload exceeds supported size');
      const destination = path.join(candidate, file.path);
      fs.mkdirSync(path.dirname(destination), { recursive: true });
      fs.writeFileSync(destination, bytes, { mode: blobs.get(file.path).mode === '100755' ? 0o755 : 0o644 });
    }
    const license = await blob('LICENSE');
    fs.writeFileSync(path.join(candidate, 'LICENSE'), license);
    fs.writeFileSync(path.join(candidate, 'manifest.json'), manifestBytes);
    const receipt = {
      schemaVersion: 1, repository: manifest.repository, source, revision, version: manifest.version,
      manifestSha256: hash(manifestBytes), managedRoot: root, discoveryRoot: discovery,
      verifiedSource: !overridden && source === canonicalSource,
      skills: manifest.skills, packageFiles: [{ path: 'LICENSE', sha256: hash(license) }],
      installedAt: new Date().toISOString(), transactionId: owner.token,
    };
    fs.writeFileSync(path.join(candidate, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n', { mode: 0o600 });
    const oldNames = new Set(previous?.manifest.skills.map(skill => skill.name) ?? []);
    const newNames = new Set(manifest.skills.map(skill => skill.name));
    const links = [...new Set([...oldNames, ...newNames])].sort().map(name => {
      const before = linkValue(name);
      if (before !== null && (!oldNames.has(name) || before !== target(name))) fail(`skill collision: ${path.join(discovery, name)}; preserve the existing entry before retrying`);
      return { name, before };
    });
    // Recheck after downloading so edits made while the network was busy cannot
    // be overwritten. The collection lock serializes cooperating installers.
    const current = inspectInstalled();
    if (!same(current, previous)) fail('managed collection changed during download; retry');
    if (previous && previous.receipt.revision === revision && previous.receipt.manifestSha256 === receipt.manifestSha256
        && previous.receipt.source === source && previous.receipt.verifiedSource === receipt.verifiedSource
        && links.every(link => link.before === target(link.name))) {
      console.log(`Gestalt skills ${manifest.version} (${revision}): unchanged`);
      return;
    }
    plainDirectory(discovery); fs.mkdirSync(discovery, { recursive: true });
    owner.journal = { original: Boolean(previous), links }; writeOwner();
    await checkpoint();
    if (previous) fs.renameSync(root, path.join(stage, 'previous'));
    await checkpoint();
    fs.renameSync(candidate, root);
    await checkpoint();
    for (const { name, before } of links) {
      if (linkValue(name) !== before) fail(`discovery entry changed during update: ${name}`);
      if (newNames.has(name)) { if (before === null) fs.symlinkSync(target(name), path.join(discovery, name)); }
      else if (before !== null) fs.unlinkSync(path.join(discovery, name));
      await checkpoint();
    }
    owner.committed = true; writeOwner();
    console.log(`Gestalt skills ${manifest.version} (${revision}): installed${receipt.verifiedSource ? '' : ' (source override; unverified)'}`);
  } catch (error) {
    try { if (!owner.committed) rollback(); }
    catch (recoveryError) { preserveRecovery = true; throw new Error(`${error.message}; rollback needs inspection: ${recoveryError.message}`); }
    throw error;
  } finally {
    if (held && !preserveRecovery) releaseLock();
  }
}
Promise.resolve().then(() => operation === 'status' ? status() : install()).catch(error => {
  console.error(`gestalt: skills: ${error.message}`);
  process.exitCode = 1;
});
JS
}

validate_transfer_source_tree() {
  local -r source=$1
  local entry invalid=''

  while IFS= read -r -d '' entry; do
    [[ $entry != *$'\n'* && $entry != *$'\r'* ]] ||
      die "skill archive paths cannot contain newlines: $entry"
  done < <(find "$source" -print0)

  invalid=$(find "$source" ! -type d ! -type f -print -quit)
  [[ -z $invalid ]] || die "skill contains an unsupported link or special file: $invalid"
}

path_is_within() {
  local -r candidate=$1
  local -r parent=$2
  [[ $candidate == "$parent" || $candidate == "$parent"/* ]]
}

copy_export_skill_root() {
  local -r source=$1
  local -r destination=$2
  local entry name resolved collection_skills=''
  local restore_dotglob=false restore_nullglob=false
  local -a entries=()

  mkdir -p -- "$destination"
  [[ -d $source ]] || return 0
  [[ ! -L $source ]] || die "skill root cannot be a symbolic link: $source"

  if ! shopt -q dotglob; then shopt -s dotglob; restore_dotglob=true; fi
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  entries=("$source"/*)
  "$restore_dotglob" && shopt -u dotglob
  "$restore_nullglob" && shopt -u nullglob

  for entry in "${entries[@]}"; do
    name=${entry##*/}
    [[ $name != '.system' ]] || continue
    if [[ -L $entry ]]; then
      resolved=$(CDPATH='' cd -- "$entry" 2>/dev/null && pwd -P) ||
        die "skill link is broken or does not target a directory: $entry"
      # Materialize only this exact managed layout as ordinary portable content.
      # Export no installer receipt, and never follow links within the payload.
      if [[ $source == "$codex_skills_root" && -d $codex_home/gestalt-skills/skills &&
            ! -L $codex_home/gestalt-skills && ! -L $codex_home/gestalt-skills/skills &&
            ! -L $codex_home/gestalt-skills/skills/$name ]]; then
        collection_skills=$(CDPATH='' cd -- "$codex_home/gestalt-skills/skills" && pwd -P)
        if [[ $resolved == "$collection_skills/$name" && $(readlink -- "$entry") == "$resolved" ]]; then
          [[ $name =~ ^[a-z0-9]+(-[a-z0-9]+)*$ && -f $resolved/SKILL.md ]] ||
            die "invalid managed collection skill: $name"
          validate_transfer_source_tree "$resolved"
          cp -a -- "$resolved" "$destination/$name"
          [[ -f $codex_home/gestalt-skills/LICENSE && ! -L $codex_home/gestalt-skills/LICENSE ]] ||
            die 'managed collection license is missing or linked; preserve it before exporting'
          if [[ ! -e $destination/$name/LICENSE ]]; then
            cp -- "$codex_home/gestalt-skills/LICENSE" "$destination/$name/LICENSE"
          fi
          ((skills_export_count += 1))
          continue
        fi
      fi
      if path_is_within "$resolved" "$user_skills_root" ||
        path_is_within "$resolved" "$managed_skills_root" ||
        path_is_within "$resolved" "$codex_skills_root"; then
        continue
      fi
      die "skill link points outside exported roots: $entry -> $resolved"
    fi
    [[ -d $entry && -f $entry/SKILL.md ]] || continue
    [[ $name =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] ||
      die "skill directory has an unsupported name: $name"
    validate_transfer_source_tree "$entry"
    cp -a -- "$entry" "$destination/$name"
    ((skills_export_count += 1))
  done
}

copy_export_profiles() {
  local -r destination=$1
  local profile name
  local restore_nullglob=false
  local -a profiles=()

  mkdir -p -- "$destination"
  [[ -d $skill_profiles_root ]] || return 0
  [[ ! -L $skill_profiles_root ]] ||
    die "skill profiles root cannot be a symbolic link: $skill_profiles_root"
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  profiles=("$skill_profiles_root"/*.yml "$skill_profiles_root"/*.yaml)
  "$restore_nullglob" && shopt -u nullglob
  for profile in "${profiles[@]}"; do
    [[ -f $profile && ! -L $profile ]] ||
      die "skill profile must be a regular file: $profile"
    name=${profile##*/}
    [[ $name =~ ^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$ ]] ||
      die "skill profile has an unsupported name: $name"
    cp -a -- "$profile" "$destination/$name"
    ((skills_export_profile_count += 1))
  done
}

command_skills_export() {
  local output output_dir output_name archive_root
  skills_export_count=0
  skills_export_profile_count=0

  (($# <= 1)) || die 'usage: gestalt skills-export [ARCHIVE]'
  require_command tar
  require_command mktemp
  require_command node

  output=${1:-$PWD/gestalt-skills.tar.gz}
  [[ $output == /* ]] || output=$PWD/$output
  output_dir=${output%/*}
  output_name=${output##*/}
  [[ -n $output_name && $output_name != '.' && $output_name != '..' ]] ||
    die "invalid skills archive path: $output"
  [[ -d $output_dir ]] || die "skills archive directory does not exist: $output_dir"
  output_dir=$(CDPATH='' cd -- "$output_dir" && pwd -P) ||
    die "could not resolve skills archive directory: $output_dir"
  output=$output_dir/$output_name
  [[ ! -e $output && ! -L $output ]] || die "refusing to overwrite skills archive: $output"

  skills_transfer_temp_root=$(mktemp -d "${TMPDIR:-/tmp}/gestalt-skills-export.XXXXXXXX") ||
    die 'could not create a temporary directory for skills export'
  archive_root=$skills_transfer_temp_root/gestalt-skills
  mkdir -p -- "$archive_root"

  copy_export_skill_root "$user_skills_root" "$archive_root/user-agents-skills"
  copy_export_skill_root "$managed_skills_root" "$archive_root/managed-skills"
  copy_export_skill_root "$codex_skills_root" "$archive_root/codex-skills"
  copy_export_profiles "$archive_root/skill-profiles"

  node --input-type=module - \
    "$archive_root/manifest.json" "$GESTALT_CLI_VERSION" \
    "$user_skills_root" "$managed_skills_root" "$codex_skills_root" \
    "$skills_export_count" "$skills_export_profile_count" "$archive_root/skill-profiles" <<'NODE'
import { writeFileSync, readFileSync, readdirSync, realpathSync, existsSync } from 'node:fs';
import { join } from 'node:path';

const [manifestPath, managerVersion, userSkillsRoot, managedSkillsRoot, codexSkillsRoot,
  skillCount, profileCount, profilesRoot] = process.argv.slice(2);
// Keep archive format 1: map canonical collection identities to the ordinary
// Codex-skill root that existing importers already relocate.
const collection = join(codexSkillsRoot, '..', 'gestalt-skills', 'skills');
if (existsSync(collection)) {
  const canonical = realpathSync(collection);
  for (const name of readdirSync(profilesRoot)) {
    const profile = join(profilesRoot, name);
    writeFileSync(profile, readFileSync(profile, 'utf8').replaceAll(canonical + '/', codexSkillsRoot + '/'));
  }
}
const manifest = {
  format: 'gestalt-skills',
  version: 1,
  managerVersion,
  sourceRoots: { userSkillsRoot, managedSkillsRoot, codexSkillsRoot },
  counts: { skills: Number(skillCount), profiles: Number(profileCount) },
};
writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });
NODE

  skills_export_staged_target=$(mktemp "$output_dir/.gestalt-skills.XXXXXXXX") ||
    die 'could not stage the skills archive'
  tar -czf "$skills_export_staged_target" -C "$skills_transfer_temp_root" gestalt-skills
  mv -- "$skills_export_staged_target" "$output"
  skills_export_staged_target=''
  rm -rf -- "$skills_transfer_temp_root"
  skills_transfer_temp_root=''
  log "exported $skills_export_count skills and $skills_export_profile_count profiles to $output"
}

validate_skills_archive() {
  local -r archive=$1
  local -r members=$skills_transfer_temp_root/members.txt
  local -r verbose=$skills_transfer_temp_root/verbose.txt
  local member normalized type duplicates=''

  tar -tzf "$archive" > "$members" || die 'could not list skills archive'
  [[ -s $members ]] || die 'skills archive is empty'
  while IFS= read -r member; do
    [[ -n $member && $member != /* ]] ||
      die "unsafe skills archive member: $member"
    case $member in *\\*) die "unsafe skills archive member: $member" ;; esac
    normalized=${member%/}
    [[ /$normalized/ != *'/../'* && /$normalized/ != *'/./'* ]] ||
      die "unsafe skills archive member: $member"
    case $normalized in
      gestalt-skills | gestalt-skills/manifest.json | \
        gestalt-skills/user-agents-skills | gestalt-skills/user-agents-skills/* | \
        gestalt-skills/managed-skills | gestalt-skills/managed-skills/* | \
        gestalt-skills/codex-skills | gestalt-skills/codex-skills/* | \
        gestalt-skills/skill-profiles | gestalt-skills/skill-profiles/*) ;;
      *) die "unexpected skills archive member: $member" ;;
    esac
  done < "$members"
  duplicates=$(sort "$members" | uniq -d | head -n 1)
  [[ -z $duplicates ]] || die "duplicate skills archive member: $duplicates"

  tar -tvzf "$archive" > "$verbose" || die 'could not inspect skills archive'
  while IFS= read -r member; do
    type=${member:0:1}
    [[ $type == '-' || $type == 'd' ]] ||
      die 'skills archive contains a link or special file'
  done < "$verbose"
}

validate_import_skill_root() {
  local -r root=$1
  local entry name
  local restore_dotglob=false restore_nullglob=false
  local -a entries=()

  [[ -d $root && ! -L $root ]] || die "skills archive directory is missing: $root"
  if ! shopt -q dotglob; then shopt -s dotglob; restore_dotglob=true; fi
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  entries=("$root"/*)
  "$restore_dotglob" && shopt -u dotglob
  "$restore_nullglob" && shopt -u nullglob
  for entry in "${entries[@]}"; do
    name=${entry##*/}
    [[ -d $entry && ! -L $entry && -f $entry/SKILL.md && ! -L $entry/SKILL.md ]] ||
      die "invalid skill in archive: $entry"
    [[ $name =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] ||
      die "skill archive contains an unsupported name: $name"
  done
}

import_skill_root() {
  local -r source=$1
  local -r destination=$2
  local entry name target
  local restore_dotglob=false restore_nullglob=false
  local -a entries=()

  [[ ! -L $destination ]] || die "destination skill root is a symbolic link: $destination"
  mkdir -p -- "$destination"
  chmod 0700 "$destination"
  if ! shopt -q dotglob; then shopt -s dotglob; restore_dotglob=true; fi
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  entries=("$source"/*)
  "$restore_dotglob" && shopt -u dotglob
  "$restore_nullglob" && shopt -u nullglob
  for entry in "${entries[@]}"; do
    name=${entry##*/}
    target=$destination/$name
    [[ ! -L $target && ( ! -e $target || -d $target ) ]] ||
      die "refusing unsafe skill destination: $target"
    if [[ -d $target ]]; then validate_transfer_source_tree "$target"; fi
    mkdir -p -- "$target"
    cp -a -- "$entry/." "$target/"
    ((skills_import_count += 1))
  done
}

import_skill_profiles() {
  local -r source=$1
  local profile name target temporary
  local restore_nullglob=false
  local -a profiles=()

  [[ -d $source && ! -L $source ]] || die 'skill profiles directory is missing from archive'
  [[ ! -L $skill_profiles_root ]] ||
    die "destination skill profiles root is a symbolic link: $skill_profiles_root"
  mkdir -p -- "$skill_profiles_root"
  chmod 0700 "$skill_profiles_root"
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  profiles=("$source"/*.yml "$source"/*.yaml)
  "$restore_nullglob" && shopt -u nullglob
  for profile in "${profiles[@]}"; do
    [[ -f $profile && ! -L $profile ]] || die "invalid skill profile in archive: $profile"
    name=${profile##*/}
    target=$skill_profiles_root/$name
    [[ ! -L $target && ( ! -e $target || -f $target ) ]] ||
      die "refusing unsafe skill profile destination: $target"
    temporary=$(mktemp "$skill_profiles_root/.gestalt-profile.XXXXXXXX") ||
      die "could not stage imported skill profile: $name"
    install -m 0600 "$profile" "$temporary"
    mv -f -- "$temporary" "$target"
    ((skills_import_profile_count += 1))
  done
}

link_imported_managed_skills() {
  local -r source=$1
  local entry name link
  local restore_nullglob=false
  local -a entries=()

  mkdir -p -- "$codex_skills_root"
  if ! shopt -q nullglob; then shopt -s nullglob; restore_nullglob=true; fi
  entries=("$source"/*)
  "$restore_nullglob" && shopt -u nullglob
  for entry in "${entries[@]}"; do
    name=${entry##*/}
    link=$codex_skills_root/$name
    if [[ ! -e $link && ! -L $link ]]; then
      ln -s -- "$managed_skills_root/$name" "$link"
    fi
  done
}

command_skills_import() {
  local -r archive_arg=${1:-}
  local archive_copy archive_root
  skills_import_count=0
  skills_import_profile_count=0

  (($# == 1)) || die 'usage: gestalt skills-import ARCHIVE'
  [[ -n $archive_arg ]] || die 'usage: gestalt skills-import ARCHIVE'
  require_command tar
  require_command mktemp
  require_command node
  require_command install
  [[ -f $archive_arg && ! -L $archive_arg ]] ||
    die "skills archive must be a regular file: $archive_arg"

  skills_transfer_temp_root=$(mktemp -d "${TMPDIR:-/tmp}/gestalt-skills-import.XXXXXXXX") ||
    die 'could not create a temporary directory for skills import'
  archive_copy=$skills_transfer_temp_root/archive.tar.gz
  install -m 0600 "$archive_arg" "$archive_copy"
  validate_skills_archive "$archive_copy"
  tar -xzf "$archive_copy" -C "$skills_transfer_temp_root"
  archive_root=$skills_transfer_temp_root/gestalt-skills

  validate_import_skill_root "$archive_root/user-agents-skills"
  validate_import_skill_root "$archive_root/managed-skills"
  validate_import_skill_root "$archive_root/codex-skills"
  [[ -f $archive_root/manifest.json && ! -L $archive_root/manifest.json ]] ||
    die 'skills archive manifest is missing'

  node --input-type=module - \
    "$archive_root/manifest.json" "$archive_root/skill-profiles" \
    "$user_skills_root" "$managed_skills_root" "$codex_skills_root" <<'NODE'
import { readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';

const [manifestPath, profilesRoot, targetUserRoot, targetManagedRoot, targetCodexRoot] =
  process.argv.slice(2);
let manifest;
try {
  manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
} catch (error) {
  throw new Error(`invalid skills archive manifest: ${error.message}`);
}
if (manifest.format !== 'gestalt-skills' || manifest.version !== 1)
  throw new Error('unsupported skills archive format or version');
const source = manifest.sourceRoots;
if (!source || typeof source !== 'object') throw new Error('skills archive source roots are missing');
const replacements = [
  [source.userSkillsRoot, targetUserRoot],
  [source.managedSkillsRoot, targetManagedRoot],
  [source.codexSkillsRoot, targetCodexRoot],
];
for (const [from, to] of replacements) {
  if (typeof from !== 'string' || !from.startsWith('/') || from === '/')
    throw new Error('skills archive contains an invalid source root');
  if (typeof to !== 'string' || !to.startsWith('/') || to === '/')
    throw new Error('skills import contains an invalid destination root');
}
replacements.sort((left, right) => right[0].length - left[0].length);
for (const entry of readdirSync(profilesRoot, { withFileTypes: true })) {
  if (!entry.isFile() || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/.test(entry.name))
    throw new Error(`invalid skill profile archive entry: ${entry.name}`);
  const path = join(profilesRoot, entry.name);
  let profile = readFileSync(path, 'utf8');
  for (const [from, to] of replacements) profile = profile.replaceAll(from, to);
  const temporary = `${path}.tmp-${process.pid}`;
  writeFileSync(temporary, profile, { mode: 0o600 });
  renameSync(temporary, path);
}
NODE

  chmod -R u+rwX,go-rwx "$archive_root"
  import_skill_root "$archive_root/user-agents-skills" "$user_skills_root"
  import_skill_root "$archive_root/managed-skills" "$managed_skills_root"
  import_skill_root "$archive_root/codex-skills" "$codex_skills_root"
  import_skill_profiles "$archive_root/skill-profiles"
  link_imported_managed_skills "$archive_root/managed-skills"

  rm -rf -- "$skills_transfer_temp_root"
  skills_transfer_temp_root=''
  log "imported $skills_import_count skills and $skills_import_profile_count profiles from $archive_arg"
}

calculate_sha256() {
  local -r file=$1

  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file"
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file"
  else
    die 'sha256sum or shasum is required to verify the manager'
  fi
}

update_manager() {
  if [[ ${GESTALT_MANAGER_DISTRIBUTION:-} == npm ]]; then
    log 'manager is installed with npm; update it with: npm install -g @jaromil/gestalt@latest'
    return 0
  fi
  # The replacement has already been installed and validated by this invocation.
  [[ $manager_update_resumed == false ]] || return 0
  local manager_source manager_dir manager_name manager_target
  local manager_download manager_replaced=false

  require_command curl
  require_command install
  require_command mktemp

  manager_source=${BASH_SOURCE[0]}
  manager_dir=$(CDPATH='' cd -- "$(dirname -- "$manager_source")" && pwd -P) ||
    die "could not resolve manager directory: $manager_source"
  manager_name=$(basename -- "$manager_source")
  manager_target=$manager_dir/$manager_name
  [[ -f $manager_target ]] || die "could not resolve manager executable: $manager_target"

  manager_update_temp_root=$(mktemp -d "${TMPDIR:-/tmp}/gestalt-update.XXXXXXXX") ||
    die 'could not create a temporary directory for the manager update'
  manager_download=$manager_update_temp_root/gestalt

  log "checking for a manager update at ${install_base_url%/}/gestalt"
  curl --fail --silent --show-error --location \
    "${install_base_url%/}/gestalt" --output "$manager_download"
  bash -n "$manager_download" || die 'downloaded manager has invalid Bash syntax'
  grep -Eq "^readonly GESTALT_CLI_VERSION='[0-9]+\.[0-9]+\.[0-9]+'$" "$manager_download" ||
    die 'downloaded manager is missing its version declaration'

  if cmp -s -- "$manager_target" "$manager_download"; then
    log "manager is already current at $manager_target"
  else
    manager_update_staged_target=$(mktemp "$manager_dir/.gestalt.XXXXXXXX") ||
      die 'could not stage the manager update'
    install -m 0755 "$manager_download" "$manager_update_staged_target"
    mv -f -- "$manager_update_staged_target" "$manager_target"
    manager_update_staged_target=''
    manager_replaced=true
    log "updated manager at $manager_target"
  fi

  rm -rf -- "$manager_update_temp_root"
  manager_update_temp_root=''
  if [[ $manager_replaced == true ]]; then
    # Preserve the complete invocation, including a detached restart worker's
    # arguments and PID. exec keeps its lock held; the new worker owns cleanup.
    log 'continuing update with the newly installed manager'
    exec bash "$manager_target" __updated-manager "${manager_invocation[@]}"
  fi
}

check_node_version() {
  local version major
  require_command node
  version=$(node -p 'process.versions.node') || die 'could not determine Node.js version'
  major=${version%%.*}
  [[ $major =~ ^[0-9]+$ ]] || die "unexpected Node.js version: $version"
  ((major >= 24)) || die "Node.js 24 or newer is required; found $version"
}

configure_codex_permissions() {
  local -r config_path=$codex_home/config.toml

  node --input-type=module - \
    "$config_path" "${BASH_SOURCE[0]}" "$codex_home" "$gestalt_home" "$HOME/.agents" \
    "$HOME/.local" "$HOME/.config" <<'NODE'
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { runInNewContext } from 'node:vm';

const configPath = process.argv[2];
const managerPath = process.argv[3];
const homeReadRoots = [...new Set(process.argv.slice(4))];
const bundle = readFileSync(managerPath, 'utf8').match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
if (!bundle) throw new Error('Bundled TOML parser missing');
const { parse } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
const source = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
parse(source); // Reject invalid input before any replacement is staged.
const newline = source.match(/\r\n|\n|\r/)?.[0] ?? '\n';
const retained = [];
let rootSection = true;
let removingSection = false;
let permissionsPosition;
let statement = '';
// Complete TOML statements keep multiline strings/arrays opaque. Retain raw
// comment, whitespace and unrelated statement bytes, including mixed newlines.
for (const line of source.match(/[^\r\n]*(?:\r\n|\n|\r|$)/g) ?? []) {
  if (!line) continue;
  statement += line;
  let parsed;
  try { parsed = parse(statement); } catch { continue; }
  const current = statement;
  statement = '';
  if (/^[ \t]*\[/.test(current)) {
    rootSection = false;
    removingSection = Boolean(parsed.sandbox_workspace_write || parsed.permissions?.['workspace-git']);
    if (removingSection) {
      permissionsPosition ??= retained.length;
      continue;
    }
  }
  if (removingSection && Object.keys(parsed).length) continue;
  if (rootSection && ['approval_policy', 'default_permissions', 'sandbox_mode'].some(key => Object.hasOwn(parsed, key))) continue;
  retained.push(current);
}
if (statement) throw new Error('Could not safely localize permissions configuration');

const root = [
  'approval_policy = "never"',
  'default_permissions = "workspace-git"',
];
const profile = [
  '[permissions.workspace-git]',
  'description = "Workspace and Git writable with local test support"',
  'extends = ":workspace"',
  '',
  '[permissions.workspace-git.network]',
  'enabled = true',
  'mode = "full"',
  'allow_local_binding = true',
  '',
  '[permissions.workspace-git.filesystem]',
  '"/tmp" = "write"',
  ...homeReadRoots.map((path) => `${JSON.stringify(path)} = "read"`),
  '',
  '[permissions.workspace-git.filesystem.":workspace_roots"]',
  '"." = "write"',
  '".git" = "write"',
  '".agents" = "read"',
  '".codex" = "read"',
];
const position = permissionsPosition ?? retained.length;
let before = retained.slice(0, position).join('');
if (before && !/[\r\n]$/.test(before)) before += newline;
// Keep the replacement at the original owned-table boundary. Moving it past
// another setup writer's table would strand that writer's separator on repeats.
// Existing comments/blank lines stay intact; generated tables add no new gaps.
const output = root.join(newline) + newline + before +
  profile.filter(line => line !== '').join(newline) + newline + retained.slice(position).join('');
parse(output);
if (output === source) process.exit(0);

mkdirSync(dirname(configPath), { recursive: true });
const temporary = `${configPath}.tmp-${process.pid}`;
writeFileSync(temporary, output, { encoding: 'utf8', mode: 0o600 });
if (existsSync(configPath)) chmodSync(temporary, statSync(configPath).mode & 0o777);
renameSync(temporary, configPath);
NODE
  log "configured workspace-git permissions in $config_path"
}

configure_codex_tool_approvals() {
  node --input-type=module - "$codex_home/config.toml" "${BASH_SOURCE[0]}" <<'NODE'
import { readFileSync, writeFileSync, renameSync, chmodSync, statSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
const [configPath, managerPath] = process.argv.slice(2);
const bundle = readFileSync(managerPath, 'utf8').match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
if (!bundle) throw new Error('Bundled TOML parser missing');
const { parse, stringify } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
const source = readFileSync(configPath, 'utf8');
const config = parse(source);
const policy = readFileSync(managerPath, 'utf8').match(/^\/\/ BEGIN MANAGED MCP APPROVAL POLICY\n([\s\S]*?)^\/\/ END MANAGED MCP APPROVAL POLICY/m);
if (!policy) throw new Error('Managed MCP approval policy missing');
const { managedMcpApprovals } = runInNewContext(policy[1] + '\n({managedMcpApprovals})');
const expected = managedMcpApprovals(config, {manager:managerPath,codexHome:configPath.slice(0,-'/config.toml'.length)});
const changes = [];
const changed = (before, after, path = []) => {
  for (const [key, value] of Object.entries(after ?? {})) {
    if (value && typeof value === 'object' && !Array.isArray(value)) changed(before?.[key], value, [...path,key]);
    else if (JSON.stringify(before?.[key]) !== JSON.stringify(value) && ['default_tools_approval_mode','approval_mode','env_vars'].includes(key)) changes.push([...path,key]);
  }
};
changed(config, expected);
if (!changes.length) process.exit(0);
// Insert into ordinary tables without discarding comments or formatting.
// Inline and dotted table definitions fall back to semantic serialization.
let output = source;
for (const fullPath of changes) {
  const path = fullPath.slice(0,-1), key = fullPath.at(-1);
  const value = fullPath.reduce((item, key) => item[key], expected);
  const rendered = stringify({[key]: value}).trimEnd();
  const header = '[' + path.map(key => JSON.stringify(key)).join('.') + ']';
  let inserted = false;
  output = output.split(/(?=^[ \t]*\[)/m).map(section => {
    const line = section.split('\n')[0];
    if (inserted || line.trimStart().startsWith('[[')) return section;
    try {
      let table = parse(line + '\n__gestalt_marker = true');
      for (const key of path) table = table?.[key];
      if (table?.__gestalt_marker !== true) return section;
      inserted = true;
      const assignment = new RegExp('^[ \\t]*'+key+'[ \\t]*=[^\\n]*','m');
      const existing = assignment.exec(section);
      if (key === 'env_vars' && existing) {
        // Extend the actual TOML array in place, retaining multiline layout,
        // comments and the operator's existing environment names.
        let end = existing.index + existing[0].length, parsed;
        while (true) {
          try { parsed = parse(section.slice(existing.index, end))[key]; break; }
          catch { const next = section.indexOf('\n', end + 1); if (next < 0) throw new Error('Incomplete environment array'); end = next; }
        }
        const original = section.slice(existing.index, end);
        let close = original.indexOf(']');
        while (close >= 0) {
          try { if (JSON.stringify(parse(original.slice(0, close + 1))[key]) === JSON.stringify(parsed)) break; } catch {}
          close = original.indexOf(']', close + 1);
        }
        if (close < 0 || !Array.isArray(parsed)) throw new Error('Invalid environment array');
        const missing = value.filter(name => !parsed.includes(name));
        if (!missing.length) return section;
        let separator = '';
        if (parsed.length) try { parse(original.slice(0, close) + ',]'); separator = ','; } catch { /* Already has a trailing comma. */ }
        const additions = stringify({env_vars: missing}).trim().replace(/^env_vars\s*=\s*\[/, '').replace(/\]$/, '');
        const updated = original.slice(0, close) + separator + ' ' + additions + original.slice(close);
        return section.slice(0, existing.index) + updated + section.slice(end);
      }
      return existing ? section.replace(assignment, rendered) : line+'\n'+rendered+section.slice(line.length);
    } catch { return section; }
  }).join('');
  if (!inserted) output += '\n' + header + '\n'+rendered+'\n';
}
const canonical = value => JSON.stringify(value, (_key, item) =>
  item && typeof item === 'object' && !Array.isArray(item)
    ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
try {
  if (canonical(parse(output)) !== canonical(expected)) output = stringify(expected);
} catch { output = stringify(expected); }
const temporary = `${configPath}.tmp-${process.pid}`;
writeFileSync(temporary, output, { mode: 0o600 });
chmodSync(temporary, statSync(configPath).mode & 0o777);
renameSync(temporary, configPath);
NODE
}

install_mobile() {
  check_node_version
  require_command npm
  mkdir -p -- "$mobile_root"
  log "installing gestalt-mobile@${mobile_version} under $mobile_root"
  npm install \
    --prefix "$mobile_root" \
    --no-audit \
    --no-fund \
    --save-exact \
    "gestalt-mobile@${mobile_version}"
  [[ -x $mobile_bin ]] || die "npm completed but the Mobile executable is missing: $mobile_bin"
}

record_setup_provenance() {
  node --input-type=module - "$codex_home" "$marketplace_setup" \
    "${BASH_SOURCE[0]}" "$GESTALT_CLI_VERSION" <<'NODE'
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const [home, setup, manager, version] = process.argv.slice(2);
const digest = path => existsSync(path)
  ? createHash('sha256').update(readFileSync(path)).digest('hex') : null;
const outputs = Object.fromEntries([
  'config.toml', 'hooks.json',
  'agents/org-plan-executor.toml', 'agents/org-plan-reviewer.toml',
].map(path => [path, digest(join(home, path))]));
const provenance = JSON.stringify({ schemaVersion: 1, scope: 'setup-artifacts-only',
  runtimeEnforcement: false, manager: { version, sha256: digest(manager) },
  delegatedSetupSha256: digest(setup), outputs }, null, 2) + '\n';
const destination = join(home, '.gestalt-setup-provenance.json');
if (existsSync(destination) && readFileSync(destination, 'utf8') === provenance) process.exit(0);
const temporary = `${destination}.tmp-${process.pid}`;
writeFileSync(temporary, provenance, { mode: 0o600 });
renameSync(temporary, destination);
NODE
}

run_marketplace_setup() {
  local -r mode=$1
  local -r include_extra_skills=$2
  local marketplace_action
  agents_setup_stage=''
  local -a setup_args=()

  check_node_version
  require_command npm
  require_command codex
  mkdir -p -- "$codex_home" "$gestalt_home"
  agents_setup_lock=$codex_home/.gestalt-setup.lock
  mkdir -- "$agents_setup_lock" 2>/dev/null ||
    die 'Agents setup is already running or Codex home is not writable; verify the previous installer exited before removing .gestalt-setup.lock'
  # Serialize setup and roll back manager-owned config edits on failure. Package
  # installation and its own profile transaction remain the delegated owner's job.
  setup_cleanup() {
    local status=$?
    trap - EXIT HUP INT TERM ERR
    # Cleanup must not replace the triggering status or prevent the manager's
    # preexisting EXIT cleanup (including the update/restart worker lock).
    set +e
    if (( status != 0 )) && [[ -n $agents_setup_stage ]]; then
      if [[ -f $agents_setup_stage/config.toml ]]; then
        mv -f -- "$agents_setup_stage/config.toml" "$codex_home/config.toml"
      elif [[ -f $agents_setup_stage/config-absent ]]; then
        rm -f -- "$codex_home/config.toml"
      fi
    fi
    [[ -z $agents_setup_stage ]] || rm -rf -- "$agents_setup_stage"
    rmdir -- "$agents_setup_lock" 2>/dev/null || true
    cleanup
    exit "$status"
  }
  trap setup_cleanup EXIT
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM
  [[ ! -L $codex_home/config.toml &&
      (! -e $codex_home/config.toml || -f $codex_home/config.toml) ]] ||
    die 'Codex config must be a regular file for setup'
  agents_setup_stage=$(mktemp -d "$codex_home/.gestalt-setup.XXXXXXXX")
  if [[ -f $codex_home/config.toml ]]; then
    cp -p -- "$codex_home/config.toml" "$agents_setup_stage/config.toml"
  else
    touch "$agents_setup_stage/config-absent"
  fi
  configure_codex_permissions
  # Establish app defaults before the owner appends its managed MCP section,
  # keeping first-install ordering identical to later reconciliation.
  configure_codex_tool_approvals

  marketplace_action=upgrade
  if [[ $mode == install && ! -f $marketplace_setup ]]; then
    marketplace_action=add
  fi

  log "${marketplace_action} marketplace $marketplace in $codex_home"
  if [[ $marketplace_action == add ]]; then
    if ! CODEX_HOME=$codex_home codex plugin marketplace add "$marketplace"; then
      log 'marketplace is already registered; attempting an upgrade'
      CODEX_HOME=$codex_home codex plugin marketplace upgrade "$marketplace_name"
    fi
  else
    if ! CODEX_HOME=$codex_home codex plugin marketplace upgrade "$marketplace_name"; then
      log 'marketplace upgrade was unavailable; attempting a fresh registration'
      CODEX_HOME=$codex_home codex plugin marketplace add "$marketplace"
    fi
  fi

  [[ -f $marketplace_setup ]] ||
    die "marketplace setup script is missing after ${marketplace_action}: $marketplace_setup"

  if [[ $include_extra_skills == true ]]; then
    setup_args+=(--extra-skills)
  fi

  log 'preparing context mode, plugins, and agent profiles'
  CODEX_HOME=$codex_home GESTALT_HOME=$gestalt_home \
    bash "$marketplace_setup" "${setup_args[@]}"
  verify_context_mode_installation
  configure_codex_tool_approvals
  # Normalize our block after delegated sections/defaults are reconciled so the
  # first successful setup has the same bytes as every subsequent setup.
  configure_codex_permissions
  record_setup_provenance
  rm -rf -- "$agents_setup_stage"
  agents_setup_stage=''
  rmdir -- "$agents_setup_lock"
  trap cleanup EXIT
  trap - HUP INT TERM
}

parse_setup_options() {
  include_extra_skills=false
  while (($# > 0)); do
    case $1 in
      --extra-skills)
        include_extra_skills=true
        ;;
      -h | --help)
        usage
        exit 0
        ;;
      *)
        die "unknown setup option: $1"
        ;;
    esac
    shift
  done
}

command_agents() {
  if (($# == 0)) || [[ $# == 1 && ( $1 == help || $1 == -h || $1 == --help ) ]]; then
    printf '%s\n' 'Usage: gestalt agents install|update' \
      'Install or reconcile Gestalt Agents and their context-mode runtime.'
    return 0
  fi
  (($# == 1)) || die 'usage: gestalt agents install|update'
  case $1 in
    install) run_marketplace_setup install false ;;
    update) run_marketplace_setup upgrade false ;;
    *) die 'usage: gestalt agents install|update' ;;
  esac
}

# Retire configuration only when its executable and complete argument contract
# prove ownership. Old processes, indexes, binaries and bare restart records
# have no transferable ownership proof; preserve them for operator inspection.
retire_managed_xerj() {
  node --input-type=module - "$codex_home" "$gestalt_home" "${BASH_SOURCE[0]}" <<'NODE'
import { readFileSync, readdirSync, lstatSync, realpathSync, openSync, writeFileSync, fchmodSync, fsyncSync, closeSync, renameSync, unlinkSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { randomBytes } from 'node:crypto';
import { runInNewContext } from 'node:vm';
const [selectedCodex, selectedHome, manager] = process.argv.slice(2);
const source = readFileSync(manager, 'utf8');
const bundle = source.match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
if (!bundle) throw new Error('Bundled TOML parser missing');
const { parse } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
const notices = new Set();
const notice = kind => notices.add(kind);
const exists = path => { try { return lstatSync(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
const canonical = path => { try { return realpathSync(path); } catch { return null; } };
const codex = canonical(selectedCodex), home = canonical(selectedHome), executable = canonical(manager);
// Home aliases are allowed. Descendant links/hardlinks are never write targets.
const plain = path => {
  const info = exists(path);
  return info?.isFile() && info.nlink === 1 && (!process.getuid || info.uid === process.getuid()) ? info : null;
};
const owned = server => server && !server.url && typeof server.command === 'string' &&
  server.command.startsWith('/') && canonical(server.command) === executable &&
  Array.isArray(server.args) && JSON.stringify(server.args) === '["xerj","mcp"]';
const related = (name, server) => /xerj/i.test(name) || server?.args?.[0] === 'xerj';
const stable = value => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
  ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
function migrate(path) {
  if (!exists(path)) return;
  const info = plain(path);
  if (!info) { notice('configuration'); return; }
  const bytes = readFileSync(path, 'utf8');
  let config;
  try { config = parse(bytes); } catch { notice('configuration'); return; }
  const names = Object.entries(config.mcp_servers ?? {}).filter(([name, server]) => {
    if (owned(server)) return true;
    if (related(name, server)) notice('configuration');
    return false;
  }).map(([name]) => name);
  if (!names.length) return;
  const expected = structuredClone(config);
  for (const name of names) delete expected.mcp_servers[name];
  // Preserve physical bytes of every unrelated section and every standalone
  // comment. Validate the entire semantic result before committing any edit;
  // inline/dotted or multiline constructs that cannot be localized stay intact.
  let removing = false;
  const output = bytes.split(/(?<=\n)/).filter(line => {
    if (/^[ \t]*\[/.test(line)) {
      removing = false;
      try {
        const table = parse(line + '\n__gestalt_retirement_marker = true\n');
        removing = names.some(name => table.mcp_servers?.[name]);
      } catch { /* Whole-result validation below rejects uncertain edits. */ }
    }
    return !removing || line.trim() === '' || /^[ \t]*#/.test(line);
  }).join('');
  // TOML does not retain empty implicit parent tables after removing children.
  if (!Object.keys(expected.mcp_servers).length) delete expected.mcp_servers;
  try { if (stable(parse(output)) !== stable(expected)) { notice('configuration'); return; } }
  catch { notice('configuration'); return; }
  if (bytes === output) return;
  const temporary = join(dirname(path), '.gestalt-retirement-' + randomBytes(12).toString('hex'));
  let handle;
  try {
    handle = openSync(temporary, 'wx', 0o600);
    writeFileSync(handle, output); fchmodSync(handle, info.mode & 0o777); fsyncSync(handle);
    closeSync(handle); handle = undefined;
    const current = plain(path);
    if (!current || current.dev !== info.dev || current.ino !== info.ino || readFileSync(path, 'utf8') !== bytes)
      throw new Error('configuration changed during Xerj retirement; retry update');
    renameSync(temporary, path);
  } finally {
    if (handle !== undefined) closeSync(handle);
    try { unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
  }
}
if (codex) {
  for (const name of readdirSync(codex).sort())
    if (name === 'config.toml' || /^[a-zA-Z0-9_-]+\.config\.toml$/.test(name)) migrate(join(codex, name));
  // No PID, socket, endpoint or record alone proves a live process belongs to
  // this updater. Do not probe it, send signals, or delete persistent data.
  if (exists(join(codex, 'xerj-data', '.lifecycle'))) notice('process records');
}
if (home && exists(join(home, 'run'))) {
  const run = join(home, 'run');
  if (!exists(run).isDirectory()) notice('restart descriptors');
  else for (const name of readdirSync(run)) if (/^mobile-[1-9][0-9]*\.restart$/.test(name)) {
    const file = join(run, name);
    if (!plain(file)) { notice('restart descriptors'); continue; }
    if (readFileSync(file).includes(Buffer.from('--xerj'))) notice('restart descriptors');
  }
}
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`);
NODE
}

command_install() {
  parse_setup_options "$@"
  command_skills install
  run_marketplace_setup install "$include_extra_skills"
  install_mobile
  log "installation complete; run 'gestalt doctor', then 'gestalt cli' or 'gestalt mobile'"
}

command_update() {
  parse_update_options "$@"
  case $update_component in
    all | gestalt)
      update_manager
      retire_managed_xerj
      command_skills update
      run_marketplace_setup upgrade "$include_extra_skills"
      install_mobile
      if [[ ${GESTALT_MANAGER_DISTRIBUTION:-} == npm ]]; then
        log 'Agents, optional skills, Mobile, and context-mode are up to date; update the manager with npm install -g @jaromil/gestalt@latest'
      else
        log 'manager, Agents, optional skills, Mobile, and context-mode are up to date'
      fi
      ;;
  esac
  if [[ $update_component == serena || ( $update_component == all && -f $gestalt_home/serena/active.json ) ]]; then
    log 'updating Serena and its private uv/Python tooling'
    command_serena update
  elif [[ $update_component == all ]]; then
    log 'skipping Serena (not installed; use gestalt update serena to install)'
  fi
  if [[ $update_component == playwright || ( $update_component == all && -f $gestalt_home/playwright/active.json ) ]]; then
    command_playwright update
  elif [[ $update_component == all ]]; then
    log 'skipping Playwright (not installed; use gestalt playwright install)'
  fi
  log "update complete ($update_component)"
}

parse_update_options() {
  include_extra_skills=false
  update_component=all
  local component_selected=false
  while (($# > 0)); do
    case $1 in
      xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
      --extra-skills) include_extra_skills=true ;;
      -h | --help) usage; exit 0 ;;
      --component)
        (($# >= 2)) || die '--component requires all, gestalt, serena, or playwright'
        [[ $component_selected == false ]] || die 'select only one update component'
        update_component=$2
        component_selected=true
        shift
        ;;
      all | gestalt | serena | playwright)
        [[ $component_selected == false ]] || die 'select only one update component'
        update_component=$1
        component_selected=true
        ;;
      *) die "unknown update option or component: $1 (run 'gestalt update --help')" ;;
    esac
    shift
  done
  case $update_component in
    xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
    all | gestalt | serena | playwright) ;;
    *) die "unknown update component: $update_component (choose all, gestalt, serena, or playwright)" ;;
  esac
  [[ $include_extra_skills == false || $update_component == all || $update_component == gestalt ]] ||
    die '--extra-skills requires the all or gestalt update component'
}

resolve_manager_target() {
  local manager_source manager_dir manager_name

  manager_source=${BASH_SOURCE[0]}
  manager_dir=$(CDPATH='' cd -- "$(dirname -- "$manager_source")" && pwd -P) ||
    die "could not resolve manager directory: $manager_source"
  manager_name=$(basename -- "$manager_source")
  manager_target=$manager_dir/$manager_name
  [[ -x $manager_target ]] || die "manager executable is unavailable: $manager_target"
}

validate_mobile_restart_context() {
  local -r relay_pid=$1
  local -r restart_state=$2
  local -r expected_state=$gestalt_home/run/mobile-$relay_pid.restart

  [[ $relay_pid =~ ^[1-9][0-9]*$ ]] ||
    die 'update-restart must be run from a session managed by Gestalt Mobile'
  [[ $restart_state == "$expected_state" && -r $restart_state ]] ||
    die 'the Gestalt Mobile restart descriptor is unavailable or invalid'
  process_is_live "$relay_pid" || die 'the managing Gestalt Mobile process is not running'
}

process_is_live() {
  local -r process_pid=$1
  local process_state

  kill -0 "$process_pid" 2>/dev/null || return 1
  process_state=$(ps -o stat= -p "$process_pid" 2>/dev/null) || return 1
  process_state=${process_state//[[:space:]]/}
  [[ $process_state != Z* ]]
}

command_update_restart() {
  local relay_pid restart_state restart_log restart_lock worker_pid manager_target

  parse_update_options "$@"
  relay_pid=${GESTALT_MOBILE_PID:-}
  restart_state=${GESTALT_MOBILE_RESTART_STATE:-}
  validate_mobile_restart_context "$relay_pid" "$restart_state"
  check_node_version
  resolve_manager_target
  restart_log=$gestalt_home/update-restart.log
  restart_lock=$gestalt_home/run/update-restart.lock
  mkdir -- "$restart_lock" 2>/dev/null ||
    die "another update-restart is already running ($restart_lock)"

  if ! worker_pid=$(node -e '
    const { spawn } = require("node:child_process");
    const [command, ...args] = process.argv.slice(1);
    const child = spawn(command, args, {
      detached: true,
      env: process.env,
      stdio: "ignore",
    });
    child.unref();
    process.stdout.write(String(child.pid));
  ' "$manager_target" __update-restart-worker \
    "$relay_pid" "$restart_state" "$include_extra_skills" "$restart_log" "$restart_lock" "$update_component"); then
    rmdir -- "$restart_lock" 2>/dev/null || true
    die 'could not schedule the detached update and restart worker'
  fi
  if [[ ! $worker_pid =~ ^[1-9][0-9]*$ ]]; then
    rmdir -- "$restart_lock" 2>/dev/null || true
    die 'the detached update worker did not start'
  fi

  log "scheduled update and Mobile restart (worker $worker_pid)"
  log "progress will be written to $restart_log; this session will reconnect after restart"
}

# Old managers stored these options in NUL-delimited restart descriptors. Adapt
# only the arguments consumed by this explicitly requested restart; unproven
# records on disk remain untouched. Never reinterpret unknown retirement values.
retire_mobile_restart_arguments() {
  migrated_restart_args=()
  while (($#)); do
    case $1 in
      --xerj)
        (($# >= 2)) || die 'legacy --xerj restart option has no value; review the restart descriptor before updating'
        case $2 in
          auto | manual | off) shift 2 ;;
          *) die 'legacy --xerj restart option is ambiguous; review the restart descriptor before updating' ;;
        esac
        ;;
      --)
        migrated_restart_args+=("$@")
        break
        ;;
      *) migrated_restart_args+=("$1"); shift ;;
    esac
  done
}

command_update_restart_worker() {
  local -r relay_pid=${1:-}
  local -r restart_state=${2:-}
  local -r worker_extra_skills=${3:-false}
  local -r restart_log=${4:-}
  local -r restart_lock=${5:-}
  local -r worker_component=${6:-all}
  local restart_cwd restart_field manager_target
  local -a restart_record restart_args migrated_restart_args update_args=()

  [[ -n $restart_log ]] || die 'the update-restart worker log path is missing'
  validate_managed_path 'update-restart log' "$restart_log"
  [[ $restart_lock == "$gestalt_home/run/update-restart.lock" && -d $restart_lock ]] ||
    die 'the update-restart worker lock is unavailable or invalid'
  update_restart_lock=$restart_lock
  mkdir -p -- "$(dirname -- "$restart_log")"
  exec >> "$restart_log" 2>&1

  log "starting live update at $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  # Let a calling Mobile endpoint flush its accepted response before any fast,
  # already-current update reaches the relay shutdown step.
  sleep 1
  validate_mobile_restart_context "$relay_pid" "$restart_state"
  while IFS= read -r -d '' restart_field; do
    restart_record+=("$restart_field")
  done < "$restart_state"
  ((${#restart_record[@]} >= 1)) || die 'the Gestalt Mobile restart descriptor is empty'
  restart_cwd=${restart_record[0]}
  restart_args=("${restart_record[@]:1}")
  retire_mobile_restart_arguments "${restart_args[@]}"
  restart_args=("${migrated_restart_args[@]}")
  [[ $restart_cwd == /* && -d $restart_cwd ]] ||
    die "the Gestalt Mobile restart directory is invalid: $restart_cwd"
  [[ $worker_extra_skills == false || $worker_extra_skills == true ]] ||
    die 'the update-restart worker received an invalid setup mode'
  if [[ $worker_extra_skills == true ]]; then
    update_args+=(--extra-skills)
  fi

  command_update "$worker_component" "${update_args[@]}"
  validate_mobile_restart_context "$relay_pid" "$restart_state"
  log "update succeeded; gracefully stopping Gestalt Mobile process $relay_pid"
  kill -TERM "$relay_pid"
  for ((attempt = 0; attempt < 300; attempt += 1)); do
    if ! process_is_live "$relay_pid"; then
      break
    fi
    sleep 0.1
  done
  process_is_live "$relay_pid" &&
    die 'Gestalt Mobile did not stop within 30 seconds; it was not force-killed'

  rm -f -- "$restart_state"
  rmdir -- "$update_restart_lock"
  update_restart_lock=''
  resolve_manager_target
  cd -- "$restart_cwd"
  log 'restarting Gestalt Mobile with its previous options'
  exec "$manager_target" mobile -- "${restart_args[@]}"
}

strip_separator() {
  if (($# > 0)) && [[ $1 == -- ]]; then
    shift
  fi
  forwarded_args=("$@")
}

# Session flags never reach persistent Codex configuration. Required, live MCP
# startup gates the actual first turn; a failed optional connection retries with
# only that capability disabled. Serena semantics are verified on the first
# policy-bearing tool call. This is native Codex stdio, not an MCP bridge.
launch_cli_with_capabilities() {
  CODEX_HOME="$codex_home" GESTALT_HOME="$gestalt_home" \
    GESTALT_MANAGER_BIN="$manager_target" GESTALT_STARTUP_DIAGNOSTICS_DONE=1 \
    PATH="$gestalt_home/bin:$codex_home/bin:$PATH" \
    exec node --input-type=module - "$@" 3<&0 <<'NODE'
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { readFile, realpath, access } from 'node:fs/promises';
import { constants } from 'node:fs';
import { resolve } from 'node:path';
import { createRequire } from 'node:module';

// BEGIN MANAGED MCP APPROVAL POLICY
function managedToolApproval(server) {
  return {...server, ...(!server.url ? {env_vars:[...new Set([...(server.env_vars ?? []),'GESTALT_SESSION_TMP_CONTEXT','TMPDIR','TMP','TEMP'])]} : {}), default_tools_approval_mode:'approve', ...(server.tools ? {tools:Object.fromEntries(
    Object.entries(server.tools).map(([name, tool]) => [name, tool && typeof tool === 'object' &&
      Object.hasOwn(tool,'approval_mode') ? {...tool,approval_mode:'approve'} : tool]))} : {})};
}
function isGestaltManagedMcp(name, server, owner) {
  if (!server || typeof server !== 'object' || server.url) return false;
  const components = {'gestalt-serena':'serena','gestalt-playwright':'playwright'};
  if (Object.hasOwn(components,name)) return (!server.command && !server.args) ||
    ([owner.manager,'gestalt'].includes(server.command) && server.args?.[0] === components[name] && server.args?.[1] === 'mcp');
  return name === 'context-mode' && String(server.command).split('/').at(-1) === 'node' &&
    server.args?.includes(owner.codexHome+'/bin/context-mode-mcp.mjs');
}
function managedMcpApprovals(config, owner) {
  const result = {...config};
  if (config.mcp_servers) result.mcp_servers = Object.fromEntries(Object.entries(config.mcp_servers)
    .map(([name,server]) => [name,isGestaltManagedMcp(name,server,owner) ? managedToolApproval(server) : server]));
  if (config.plugins) result.plugins = Object.fromEntries(Object.entries(config.plugins).map(([name,plugin]) =>
    [name,name === 'context-mode@dyne-gestalt-agents' && plugin?.mcp_servers ? {...plugin,mcp_servers:Object.fromEntries(
      Object.entries(plugin.mcp_servers).map(([serverName,server]) => [serverName,serverName === 'context-mode' ? managedToolApproval(server) : server]))} : plugin]));
  return result;
}
function managedMcpOverrides(config, baseline, owner) {
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
  const omitAbsent = value => Array.isArray(value) ? value.map(omitAbsent) : object(value) ?
    Object.fromEntries(Object.entries(value).filter(([,v]) => v !== null).map(([k,v]) => [k,omitAbsent(v)])) : value;
  const merge = (base, options) => {
    const result = {...base};
    if (Object.hasOwn(options,'url') && !Object.hasOwn(options,'command'))
      for (const key of ['command','args','cwd','env','env_vars']) delete result[key];
    if (Object.hasOwn(options,'command') && !Object.hasOwn(options,'url')) delete result.url;
    for (const [key,value] of Object.entries(options)) Object.defineProperty(result,key,{value:
      object(value) ? merge(object(result[key]) ? result[key] : {},value) : value,enumerable:true,configurable:true,writable:true});
    return result;
  };
  // Preserve effective native transports and enablement. Absent inherited nulls
  // cannot be round-tripped through Codex's JSON-to-TOML config overrides.
  const result = {...config};
  for (const section of ['mcp_servers','plugins']) {
    let effective = merge(omitAbsent(baseline?.[section] ?? {}),config?.[section] ?? {});
    for (const key of Object.keys(result).filter(key => key.startsWith(section+'.')).sort()) {
      let value = result[key];
      for (const part of key.slice(section.length+1).split('.').reverse()) value = {[part]:value};
      effective = merge(effective,value);
    }
    const approved = managedMcpApprovals({[section]:effective},owner)[section];
    // Do not serialize unrelated inherited settings/credentials into overrides.
    const changed = Object.fromEntries(Object.entries(approved).filter(([name,server]) =>
      JSON.stringify(server) !== JSON.stringify(effective[name])));
    for (const name of Object.keys(changed)) for (const key of Object.keys(result))
      if (key === section+'.'+name || key.startsWith(section+'.'+name+'.')) delete result[key];
    if (Object.keys(changed).length || config?.[section]) result[section] = merge(config?.[section] ?? {},changed);
  }
  return result;
}
// END MANAGED MCP APPROVAL POLICY

// BEGIN BUNDLED PROFILE TOML PARSER
/* smol-toml 1.9.0 (BSD-3-Clause)
Copyright (c) Squirrel Chat et al., All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var gestaltProfileToml=(()=>{var D=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var K=(e,r)=>{for(var i in r)D(e,i,{get:r[i],enumerable:!0})},F=(e,r,i,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of U(r))!W.call(e,a)&&a!==i&&D(e,a,{get:()=>r[a],enumerable:!(t=j(r,a))||t.enumerable});return e};var R=e=>F(D({},"__esModule",{value:!0}),e);var le={};K(le,{parse:()=>E,stringify:()=>$});function q(e,r){let i=e.slice(0,r).split(/\r?\n/);return[i.length,i.pop().length+1]}function G(e,r,i){let t=e.split(/\r?\n/),a="",l=(Math.log10(r+1)|0)+1;for(let n=r-1;n<=r+1;n++){let s=t[n-1];s&&(a+=n.toString().padEnd(l," "),a+=":  ",a+=s,a+=`
`,n===r&&(a+=" ".repeat(l+i+2),a+=`^
`))}return a}var o=class e extends Error{line;column;codeblock;constructor(r,i){let[t,a]=q(i.toml,i.ptr),l=G(i.toml,t,a);super(`Invalid TOML document: ${r}

${l}`,i),this.line=t,this.column=a,this.codeblock=l}static x(r,i,t){throw new e(r,{toml:i.s,ptr:t??i.p})}};function y(e){let r=e.p,i=e.s.charCodeAt(e.p++),t=i,a=i===39,l=i===e.s.charCodeAt(e.p)&&i===e.s.charCodeAt(e.p+1);l&&((i=e.s.charCodeAt(e.p+=2))===10?e.p++:i===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let n="",s=e.p,f=0;for(;e.p<e.s.length;e.p++)if(i=e.s.charCodeAt(e.p),l&&(i===10||i===13&&e.s.charCodeAt(e.p+1)===10))f=f&&3;else if(i<32&&i!==9||i===127)o.x("control characters are not allowed in strings",e);else if((!f||f===3)&&i===t&&(!l||e.s.charCodeAt(e.p+1)===t&&e.s.charCodeAt(e.p+2)===t)){if(l&&(e.s.charCodeAt(e.p+3)===t&&e.p++,e.s.charCodeAt(e.p+3)===t&&e.p++),!f){let u=e.s.slice(s,e.p);n=n?n+u:u}return e.p+=l?3:1,n}else if(!f)!a&&i===92&&(n+=e.s.slice(s,s=e.p),f=1);else if(f===1)if(i===120||i===117||i===85){let u=e.p++-1,p=0,d=i===120?2:i===117?4:8;for(let g=0;g<d;g++,e.p++){let m=e.s.charCodeAt(e.p),N=m>=48&&m<=57?m-48:m>=65&&m<=70?m-65+10:m>=97&&m<=102?m-97+10:-1;N<0&&o.x("invalid non-hex character in unicode escape",e),p=p<<4|N}(p<0||p>1114111||p>=55296&&p<=57343)&&o.x("invalid unicode escape",e,u),n+=String.fromCodePoint(p),s=e.p--,f=0}else l&&(i===32||i===9)?f=2:(i===98?n+="\b":i===116?n+="	":i===110?n+=`
`:i===102?n+="\f":i===114?n+="\r":i===101?n+="\x1B":i===34?n+='"':i===92?n+="\\":o.x("unrecognised escape sequence",e),s=e.p+1,f=0);else i!==32&&i!==9&&(f===2&&o.x("invalid escape: only line-ending whitespace may be escaped",e,s),f=!a&&i===92?1:0,s=e.p);o.x("unfinished string",e,r)}var Y=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,C=class e extends Date{#r=!1;#i=!1;#e=null;constructor(r,i,t){let a=!0,l=!0,n="Z",s;if(typeof r=="string")if(i)e:{if(i<3){if(+r.slice(11,13)>23){r="";break e}i===2?(n=null,r+="Z"):(s=r.charCodeAt(r.length-1))!==90&&s!==122&&(n=r.slice(r.length-6)),t&&(r=r.slice(0,10)+"T"+r.slice(11))}else i===4&&(r=+r.slice(0,2)>23?"":`0000-01-01T${r}Z`);a=i!==4,l=i!==3}else{let f=r.match(Y);f?(f[1]||(a=!1,r=`0000-01-01T${r}`),l=!!f[2],l&&r[10]===" "&&(r=r.replace(" ","T")),f[2]&&+f[2]>23?r="":(n=f[3]||null,!n&&l&&(r+="Z"))):r=""}super(r),isNaN(this.getTime())||(this.#r=a,this.#i=l,this.#e=n)}isDateTime(){return this.#r&&this.#i}isLocal(){return!this.#r||!this.#i||!this.#e}isDate(){return this.#r&&!this.#i}isTime(){return this.#i&&!this.#r}isValid(){return this.#r||this.#i}toISOString(){let r=super.toISOString();if(this.isDate())return r.slice(0,10);if(this.isTime())return r.slice(11,23);if(this.#e===null)return r.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return r;let i=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return i=this.#e[0]==="-"?i:-i,new Date(this.getTime()-i*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(r,i="Z"){let t=new e(r);return t.#e=i,t}static wrapAsLocalDateTime(r){let i=new e(r);return i.#e=null,i}static wrapAsLocalDate(r){let i=new e(r);return i.#i=!1,i.#e=null,i}static wrapAsLocalTime(r){let i=new e(r);return i.#r=!1,i.#e=null,i}};function h(e,r=10){return r===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+r}function v(e,r){return e===32||e===9||e===10||e===13||r&&(e===r||e===44)||e===35}function w(e,r){let i=e.p,t=e.s.charCodeAt(e.p);if(t===91||t===123){e.d--||o.x("document contains excessively nested structures. aborting.",e);let a=t===91?z(e):Z(e);return e.d++,a}return t===34||t===39?y(e):t===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&o.x("invalid value",e,i),e.p++,!0):t===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&o.x("invalid value",e,i),e.p++,!1):t===43||t===45?c(e,e.p,e.s.charCodeAt(++e.p),44-t,r):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?H(e,t,r):e.s.charCodeAt(e.p+2)===58?J(e,t,r):c(e,e.p,t,0,r)}function c(e,r,i,t,a){let l=i,n=0,s=!1;if(l===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&o.x("invalid value",e,r),e.p++,(t||1)/0;if(l===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&o.x("invalid value",e,r),e.p++,NaN;if(l===48){if(++e.p>=e.s.length||v(l=e.s.charCodeAt(e.p),a))return e.bi===!0?0n:0;if(!t){if(l===120)return O(e,r,16,a);if(l===98)return O(e,r,2,a);if(l===111)return O(e,r,8,a)}l===46?n=2:l===101||l===69?n=4:o.x("illegal leading zero",e,r)}else h(l)||o.x("invalid value",e,r);for(;++e.p<e.s.length&&(l=e.s.charCodeAt(e.p),!v(l,a));)n||(n=1),l===95?(n&1||o.x("illegal underscore",e),n+=11,s=!0):n===1&&l===46?n=2:(n===1||n===3)&&(l===101||l===69)?n=4:n===4&&(l===43||l===45)||(h(l)?n>9?n-=11:n&1||n++:o.x("illegal character in numeric literal",e));if(!n){let u=(i-48)*(t||1);return e.bi===!0?BigInt(u):u}n&1||o.x("unfinished numeric value",e,r);let f=e.s.slice(r,e.p);return s&&(f=f.replaceAll("_","")),n>1?parseFloat(f):P(e,f,10,r)}function O(e,r,i,t){let a,l=1;for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!v(a,t));)a===95?(l&1&&o.x("illegal underscore",e),l=3):h(a,i)?l&1&&l--:o.x("illegal character in numeric literal",e);l&1&&o.x("unfinished numeric value",e);let n=e.s.slice(r+2,e.p);return l&&(n=n.replaceAll("_","")),P(e,n,i,r)}function P(e,r,i,t){if(e.bi!==!0)e:{let a=parseInt(r,i);if(!Number.isSafeInteger(a)){if(e.bi)break e;o.x("integer value cannot be represented losslessly",e,t)}return a}return BigInt(i===10?r:(i===2?"0b":i===8?"0o":"0x")+r)}function H(e,r,i){let t=e.p++,a;if(!h(r)||!h(e.s.charCodeAt(e.p++))||!h(e.s.charCodeAt(e.p++))||!h(e.s.charCodeAt(e.p++)))return c(e,e.p=t,r,0,i);if(e.p+=5,h(e.s.charCodeAt(e.p++))||o.x("invalid date-time: date part is malformed",e,t),e.p>=e.s.length||((r=e.s.charCodeAt(e.p))!==32||(a=!0,!h(e.s.charCodeAt(e.p+1))))&&r!==84&&r!==116){let n=e.s.slice(t,e.p);return T(e,n,3,!1,t)}if(e.s.charCodeAt(e.p+=3)!==58&&o.x("invalid date-time: time part is malformed",e,t),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;h(e.s.charCodeAt(++e.p)););if(r=e.s.charCodeAt(e.p)){if(r===90||r===122){let n=e.s.slice(t,++e.p);return T(e,n,1,a,t,"[+00:00]")}if(r===43||r===45){let n=e.s.slice(t,e.p+=6);return T(e,n,1,a,t,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let l=e.s.slice(t,e.p);return T(e,l,2,a,t)}function J(e,r,i){let t=e.p;if(!h(r)||!h(e.s.charCodeAt(++e.p)))return c(e,--e.p,r,0,i);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;h(e.s.charCodeAt(++e.p)););let a=e.s.slice(t,e.p);return T(e,a,4,!1,t)}function T(e,r,i,t,a,l){if(e.ld){let n=new C(r,i,t);return n.isValid()||o.x("invalid date",e,a),n}try{switch(l&&(r+=l),i){case 1:return Temporal.ZonedDateTime.from(r);case 2:return Temporal.PlainDateTime.from(r);case 3:return Temporal.PlainDate.from(r);case 4:return Temporal.PlainTime.from(r)}}catch(n){o.x(n instanceof Error?n.message:""+n,e,a)}}function Q(e){for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===10)break;if(r===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(r<32&&r!==9||r===127)&&o.x("control characters are not allowed in comments",e)}}function A(e,r,i){let t;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((t=e.s.charCodeAt(e.p))===32||t===9||!r&&(t===10||t===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(i||t!==35)break;Q(e)}}function k(e,r=61){let i,t=0,a=[],l,n=e.s.charCodeAt(i=e.p);do{if(n===r)return t||o.x("unexpected end of key",e),t===1&&a.push(e.s.slice(l,e.p)),e.p++,a;n===46?(t||o.x("illegal empty bare key",e),t===1&&a.push(e.s.slice(l,e.p)),t=0):!t&&(n===34||n===39)?(n===e.s.charCodeAt(e.p+1)&&n===e.s.charCodeAt(e.p+2)&&o.x("illegal quoted key: multiline strings are not allowed",e),a.push(y(e)),t=2,e.p--):n===32||n===9?t===1&&(a.push(e.s.slice(l,e.p)),t=2):t===2||n<48&&n!==45||n>57&&n<65||n>90&&n<97&&n!==95||n>122?o.x("illegal character in key",e):t||(t=1,l=e.p)}while(n=e.s.charCodeAt(++e.p));o.x("incomplete key-value: cannot find end of key",e,i)}function Z(e){let r=e.p++,i=Object.create(null),t=new Set,a;for(;e.p<e.s.length;){if(A(e),(a=e.s.charCodeAt(e.p))===125)return e.p++,i;let l,n=i,s=!1,f=e.p,u=k(e);for(let d=0;d<u.length;d++){d&&(n=s?n[l]:n[l]=Object.create(null)),l=u[d],(s=Object.hasOwn(n,l))&&(typeof n[l]!="object"||t.has(n[l]))&&o.x("trying to redefine an already defined value",e,f);let g=l==="__proto__";if(e.uk&&(g||l==="constructor")){n=e.uk!==1&&o.x("document contains an unsafe property",e,f);break}!s&&g&&Object.defineProperty(n,l,{enumerable:!0,configurable:!0,writable:!0})}s&&o.x("trying to redefine an already defined value",e,f),A(e,!0,!0);let p=w(e,125);if(n&&typeof(n[l]=p)=="object"&&t.add(p),A(e),(a=e.s.charCodeAt(e.p++))===125)return i;a!==44&&o.x("expected comma or end of structure",e,e.p-1)}o.x("unfinished table",e,r)}function z(e){let r=e.p++,i=[],t;for(;e.p<e.s.length;){if(A(e),(t=e.s.charCodeAt(e.p))===93)return e.p++,i;if(i.push(w(e,93)),A(e),(t=e.s.charCodeAt(e.p++))===93)return i;t!==44&&o.x("expected comma or end of structure",e,e.p-1)}o.x("unfinished array",e,r)}function L(e,r,i,t,a){let l=i,n=t,s,f=!1,u;for(let p=0;p<r.length;p++){if(p){if(l=f?l[s]:l[s]=Object.create(null),n=(u=n[s]).c,a===0&&(u.t===1||u.t===2))return null;if(u.t===2){let d=l.length-1;l=l[d],n=n[d].c}}if(s=r[p],(f=Object.hasOwn(l,s))&&n[s]?.t===0&&n[s]?.d)return null;if(!f){let d=s==="__proto__";if(e.uk&&(d||s==="constructor"))return!1;d&&(Object.defineProperty(l,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(n,s,{enumerable:!0,configurable:!0,writable:!0})),n[s]={t:p<r.length-1&&a===2?3:a,d:!1,i:0,c:Object.create(null)}}}if(u=n[s],u.t!==a&&!(a===1&&u.t===3)||(a===2&&(u.d||(u.d=!0,l[s]=[]),l[s].push(l=Object.create(null)),u.c[u.i++]=u={t:1,d:!1,i:0,c:Object.create(null)}),u.d))return null;if(u.d=!0,a===1)l=f?l[s]:l[s]=Object.create(null);else if(a===0&&f)return null;return[s,l,u.c]}function V(e,r,i){(r===null||e.uk===2)&&o.x(r===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,i)}function E(e,r={}){let i={s:e,p:0,d:r.maxDepth??1e3,bi:r.integersAsBigInt??!1,ld:r.useLegacyDate??!0,uk:r.unsafeKeyBehaviour==="throw"?2:r.unsafeKeyBehaviour==="drop"?1:0},t=Object.create(null),a=Object.create(null),l,n=!1,s=t,f=a;for(e.charCodeAt(0)===65279&&i.p++,A(i);i.p<e.length;){if(e.charCodeAt(i.p)===91){let u=e.charCodeAt(++i.p)===91;l=i.p+=+u,n=!1;let p=k(i,93);u&&(e.charCodeAt(i.p)!==93&&o.x("expected end of table array declaration",i),i.p++);let d=L(i,p,t,a,u?2:1);d?(f=d[2],s=d[1]):(V(i,d,l),n=!0)}else{l=i.p;let u=k(i),p=L(i,u,s,f,0);!p&&!n&&V(i,p,l),A(i,!0,!0);let d=w(i,void 0);p&&!n&&(p[1][p[0]]=d)}A(i,!0),i.p<e.length&&(l=e.charCodeAt(i.p))!==10&&(l!==13||e.charCodeAt(i.p+1)!==10)&&o.x("each key-value declaration must be followed by an end-of-line",i),A(i)}return t}var X=/^[a-z0-9-_]+$/i,_=!!"".isWellFormed;function b(e){let r=typeof e;if(r==="object"){if(Array.isArray(e))return"array";if(typeof e.getUTCDate=="function"&&e instanceof Date)return"date";if(globalThis.Temporal){if(e.until){if(e instanceof Temporal.ZonedDateTime)return"temporal/tz+uc";if(e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainDate)return"temporal/uc";if(e instanceof Temporal.PlainTime||e instanceof Temporal.Instant)return"temporal";if(e instanceof Temporal.PlainYearMonth)return"temporal/x"}else if(e.toPlainDate&&e instanceof Temporal.PlainMonthDay||e.negated&&e instanceof Temporal.Duration)return"temporal/x"}}return r}function x(e){for(let r=0;r<e.length;r++)if(b(e[r])!=="object")return!1;return e.length!=0}function B(e){return JSON.stringify(e).replaceAll("\x7F","\\u007f")}function ee(e){return B(_?e.toWellFormed():e)}function M(e){if(X.test(e))return e;if(_&&!e.isWellFormed())throw new RangeError("key contains illegal lone surrogates");return B(e)}function S(e,r,i,t,a){if(i===0)throw new Error("Could not stringify the object: maximum object depth exceeded");switch(r){case"number":if(isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Number.isInteger(e)&&(t||!Number.isSafeInteger(e)))return e.toFixed(1);case"bigint":case"boolean":case"temporal":return e.toString();case"string":return ee(e);case"date":if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString();case"object":return re(e,i,t,a);case"array":return ie(e,i,t,a);case"temporal/tz+uc":if(a){let l=e.timeZoneId,n=l.charCodeAt(0);if(n!==43&&n!==45&&(n!==85&&n!==71&&n!==90&&n!==69||l!=="UTC"&&l!=="UCT"&&l!=="Universal"&&l!=="Zulu"&&!l.startsWith("GMT")&&l!=="Greenwich"&&!l.startsWith("Etc/")))throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode")}case"temporal/uc":if(a&&e.calendarId!=="iso8601")throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");return e.toString({calendarName:"never",timeZoneName:"never"});case"temporal/x":throw new TypeError("Unsupported "+e[Symbol.toStringTag])}}function re(e,r,i,t){let a=Object.keys(e);if(a.length===0)return"{}";let l="{ ";for(let n=0;n<a.length;n++){let s=a[n];n&&(l+=", "),l+=M(s)+" = "+S(e[s],b(e[s]),r-1,i,t)}return l+" }"}function ie(e,r,i,t){if(e.length===0)return"[]";let a="[ ";for(let l=0;l<e.length;l++){if(l&&(a+=", "),e[l]===null||e[l]===void 0)throw new TypeError("arrays cannot contain null or undefined values");a+=S(e[l],b(e[l]),r-1,i,t)}return a+" ]"}function ne(e,r,i,t,a){if(i===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let l="";for(let n=0;n<e.length;n++)l+=`${l&&`
`}[[${r}]]
`,l+=I(0,e[n],r,i,t,a);return l}function I(e,r,i,t,a,l){if(t===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let n="",s="",f=Object.keys(r);for(let u=0;u<f.length;u++){let p=f[u];if(r[p]!==null&&r[p]!==void 0){let d=b(r[p]);if(d==="symbol"||d==="function")throw new TypeError(`cannot serialize values of type '${d}'`);let g=M(p);if(d==="array"&&x(r[p]))s+=(s&&`
`)+ne(r[p],i?`${i}.${g}`:g,t-1,a,l);else if(d==="object"){let m=i?`${i}.${g}`:g;s+=(s&&`
`)+I(m,r[p],m,t-1,a,l)}else n+=g,n+=" = ",n+=S(r[p],d,t,a,l),n+=`
`}}return e&&(n||!s)&&(n=n?`[${e}]
${n}`:`[${e}]`),n&&s?`${n}
${s}`:n||s}function $(e,{maxDepth:r=1e3,numbersAsFloat:i=!1,strictTemporal:t=!1}={}){if(b(e)!=="object")throw new TypeError("stringify can only be called with an object");let a=I(0,e,"",r,i,t);return a[a.length-1]!==`
`?a+`
`:a}return R(le);})();
// END BUNDLED PROFILE TOML PARSER
const args = process.argv.slice(2);
const manager = process.env.GESTALT_MANAGER_BIN;
const scratchNames=['GESTALT_SESSION_TMP_CONTEXT','TMPDIR','TMP','TEMP'];
const environment={...process.env};
let cliOwned=false,scratchApi;
if(Object.hasOwn(environment,scratchNames[0])) {
 const source=(await readFile(manager,'utf8')).match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
 if(!source)throw Error('managed scratch runtime missing');
 scratchApi=new Function('require',source[1]+'\nreturn {scratchEnvironment,scratchJson,scratchBorrow,scratchRelease,scratchStopped};')(createRequire(import.meta.url));
 Object.assign(environment,scratchApi.scratchEnvironment(environment));
 cliOwned=scratchApi.scratchJson(JSON.parse(environment.GESTALT_SESSION_TMP_CONTEXT).markerPath).ownerKind==='cli-session';
}
const discoveryEnvironment={...environment};
if(Object.hasOwn(discoveryEnvironment,scratchNames[0]))for(const name of scratchNames)delete discoveryEnvironment[name];
let mappingUnknown=false;
const protectUnknownMapping=()=>{
 if(cliOwned&&!mappingUnknown){mappingUnknown=true;scratchApi.scratchBorrow(JSON.parse(environment.GESTALT_SESSION_TMP_CONTEXT),'cli-provider-mapping-unknown');
 process.stderr.write('gestalt: native provider association unavailable; CLI temporary owner remains protected\n');}
};
const budget = 5000;
// One deadline covers native discovery, shared readiness and MCP startup.
let readinessDeadline = Date.now() + budget;
let currentChild;
let playwrightController;
let interrupted = false;
let interruptionCode = 130;
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => {
  interrupted = true;
  interruptionCode = signal === 'SIGINT' ? 130 : 143;
  currentChild?.kill(signal);
});
const diagnose = reason => process.stderr.write(`gestalt: capability discovery unavailable (${reason}); continuing with native tools\n`);
const toml = value => {
  if (typeof value === 'string') return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(toml).join(',')}]`;
  if (value && typeof value === 'object') return `{${Object.entries(value).filter(([, v]) => v != null)
    .map(([k, v]) => `${JSON.stringify(k)}=${toml(v)}`).join(',')}}`;
  return String(value);
};
const appendFlags = flags => {
  const end = args.indexOf('--');
  const boundary = end < 0 ? args.length : end;
  // Codex 0.160 replaces the root repeated-config list when another config
  // flag appears at subcommand scope. Add at the user's selected parse level,
  // after its overrides, without moving or copying any original user argument.
  const index = configInsertion ?? boundary;
  // Ordinary session overrides use an embedded server. Managed Playwright
  // instead supplies its own remote frontend; --no-daemon conflicts there.
  // An explicit user --no-daemon stays untouched and selects the ordinary path.
  const mode = remote || playwrightController || args.slice(0, boundary).includes('--no-daemon') ? [] : ['--no-daemon'];
  return [...mode, ...args.slice(0, index), ...flags.flatMap(flag => ['-c', flag]), ...args.slice(index)];
};
const flags = [];
let cwd = process.cwd();
let rawSkillConfig;
let explicitSkills = {};
let remote = false;
let namedProfile;
let configInsertion;
for (let i = 0; i < args.length && args[i] !== '--'; i++) {
  const option = args[i];
  let config;
  if (option === '-c' || option === '--config') config = args[++i];
  else if (option.startsWith('--config=')) config = option.slice(9);
  else if (option.startsWith('-c') && option.length > 2) config = option.slice(2);
  if (config !== undefined) {
    configInsertion = i + 1;
    flags.push('-c', config);
    const boundary = config.indexOf('=');
    const key = config.slice(0, boundary).trim();
    if (key === 'skills' || key === 'skills.config') {
      try {
        const value = gestaltProfileToml.parse('value=' + config.slice(boundary + 1)).value;
        if (key === 'skills') explicitSkills = value; else explicitSkills.config = value;
      } catch { /* Native CLI still receives the original invalid override. */ }
    }
    if (/^skills\.config\s*=/.test(config)) rawSkillConfig = config.slice(config.indexOf('=') + 1).trim();
  } else if (option === '-C' || option === '--cd') cwd = resolve(cwd, args[++i] ?? '.');
  else if (option.startsWith('--cd=')) cwd = resolve(cwd, option.slice(5));
  else if (option.startsWith('-C') && option.length > 2) cwd = resolve(cwd, option.slice(2));
  else if (option === '-p' || option === '--profile') { namedProfile = args[++i]; }
  else if (option.startsWith('--profile=')) namedProfile = option.slice(10);
  else if (option.startsWith('-p') && option.length > 2) namedProfile = option.slice(2);
  else if (option === '--enable' || option === '--disable') flags.push('-c', `features.${args[++i]}=${option === '--enable'}`);
  else if (option.startsWith('--enable=') || option.startsWith('--disable=')) {
    const [setting, feature] = option.split('=', 2);
    flags.push('-c', `features.${feature}=${setting === '--enable'}`);
  }
  else if (option.startsWith('--remote')) remote = true;
}

async function snapshot(extra = [], hooksOnly = false, beforeFlags = false, deadline = readinessDeadline) {
  const remaining = Math.max(0, deadline - Date.now());
  if (!remaining) throw new Error('readiness-deadline');
  const child = spawn('codex', ['app-server', '--stdio', ...(beforeFlags ? extra.flatMap(value => ['-c', value]) : []), ...flags, ...(!beforeFlags ? extra.flatMap(value => ['-c', value]) : [])], {
    cwd, env: discoveryEnvironment, stdio: ['pipe', 'pipe', 'ignore'],
  });
  const previousChild = currentChild;
  currentChild = child;
  const pending = new Map();
  let id = 0;
  const fail = () => { for (const value of pending.values()) value.reject(new Error('config-unavailable')); pending.clear(); };
  child.on('error', fail);
  child.on('exit', fail);
  child.stdin.on('error', fail);
  const lines = createInterface({ input: child.stdout });
  lines.on('line', line => {
    let message;
    try { message = JSON.parse(line); } catch { return; }
    const waiter = pending.get(message.id);
    if (!waiter) return;
    pending.delete(message.id);
    message.error ? waiter.reject(new Error('config-unavailable')) : waiter.resolve(message.result);
  });
  const request = (method, params) => new Promise((resolve, reject) => {
    const next = ++id;
    pending.set(next, { resolve, reject });
    child.stdin.write(`${JSON.stringify({ id: next, method, params })}\n`);
  });
  const timer = setTimeout(() => { fail(); child.kill(); }, Math.min(5000, remaining));
  try {
    const initialized = await request('initialize', { clientInfo: { name: 'gestalt-capability-config', version: '1' }, capabilities: {} });
    child.stdin.write(`${JSON.stringify({ method: 'initialized', params: {} })}\n`);
    if (hooksOnly) return await request('hooks/list', { cwds: [cwd] });
    const config = await request('config/read', { cwd, includeLayers: true });
    const skills = await request('skills/list', { cwds: [cwd], forceReload: true });
    return { config: config.config, layers: config.layers ?? [], skills: skills.data?.find(entry => entry.cwd === cwd)?.skills ?? [],
      version: initialized.userAgent ?? '' };
  } finally {
    clearTimeout(timer);
    lines.close();
    child.stdin.end();
    child.kill();
    await new Promise(resolve => child.exitCode != null || child.signalCode != null ? resolve() : child.once('exit', resolve));
    currentChild = previousChild;
  }
}

async function launch(launchArgs) {
  if (playwrightController) return playwrightController(launchArgs);
  const child = spawn('codex', launchArgs, { cwd: process.cwd(), env: environment,
    // Node's own stdin carries this program. Open the inherited terminal/stdin
    // separately so prompts and EOF retain normal Codex behavior.
    stdio: [3, 'inherit', 'pipe'] });
  currentChild = child;
  let tail = '';
  const startupFailed = new Set();
  child.stderr.on('data', data => {
    process.stderr.write(data);
    tail = (tail + data.toString()).slice(-8192);
    // Scope names to the required-failure diagnostic, not unrelated stderr.
    for (const diagnostic of tail.matchAll(/required MCP servers failed to initialize:([^\r\n]*)/g))
      for (const name of ['gestalt-serena'])
        if (new RegExp(`(?:^|[\\s,;])${name}:`).test(diagnostic[1])) startupFailed.add(name);
  });
  const result = await new Promise(resolve => {
    child.once('error', () => resolve({ code: 127 }));
    child.once('exit', (code, signal) => resolve({ code: code ?? (signal === 'SIGINT' ? 130 : 143) }));
  });
  currentChild = undefined;
  return { ...result, startupFailed };
}

let state;
try { state = await snapshot(); } catch { diagnose('native-config-unavailable'); }
// Codex 0.160 profile-v2 files overlay the base user layer, then projects
// and session flags win. Only readiness-relevant settings are adapted; the
// actual CLI retains --profile and loads all other settings natively.
const profileKeys = ['approval_policy', 'mcp_servers', 'plugins', 'skills', 'hooks', 'features', 'projects', 'developer_instructions'];
const table = value => value && typeof value === 'object' && !Array.isArray(value);
const merge = (base, overlay) => {
  for (const [key, value] of Object.entries(overlay ?? {})) {
    if (table(value) && table(base[key])) merge(base[key], value);
    else base[key] = structuredClone(value);
  }
  return base;
};
async function resolveNamedProfile(state, deadline = readinessDeadline, includeSkills = true) {
  if (!state || !namedProfile) return state;
    if (!/^[a-zA-Z0-9_-]+$/.test(namedProfile)) throw new Error('invalid-profile');
    const profile = gestaltProfileToml.parse(await readFile(resolve(environment.CODEX_HOME, namedProfile + '.config.toml'), 'utf8'));
    const originalSession = state.layers.find(layer => layer.name?.type === 'sessionFlags');
    // Profile trust settings participate in native project discovery.
    if (profile.projects) {
      const discovered = await snapshot([`projects=${toml(profile.projects)}`], false, true, deadline);
      state.layers = discovered.layers.filter(layer => layer.name?.type !== 'sessionFlags');
      if (originalSession) state.layers.unshift(originalSession);
    }
    const effective = {};
    let inserted = false;
    for (const layer of [...state.layers].reverse()) {
      if (!layer.disabledReason) merge(effective, Object.fromEntries(Object.entries(layer.config).filter(([key]) => profileKeys.includes(key))));
      if (layer.name?.type === 'user' && !layer.name.profile) {
        merge(effective, Object.fromEntries(Object.entries(profile).filter(([key]) => profileKeys.includes(key))));
        inserted = true;
      }
    }
    if (!inserted) throw new Error('profile-layer-unavailable');
    state.config = { ...state.config, ...effective };
    // Plugin inclusion is discovered by the native catalog, not inferred from
    // the profile text. No credentials or unrelated settings enter argv.
    if (profile.plugins && includeSkills) {
      const discovered = await snapshot([`plugins=${toml(effective.plugins ?? {})}`], false, false, deadline);
      state.skills = discovered.skills;
    }
  return state;
}
try { state = await resolveNamedProfile(state); } catch { state = undefined; diagnose('profile-discovery-unavailable'); }
const session = state?.layers?.find(layer => layer.name?.type === 'sessionFlags')?.config ?? {};
let rules = session.skills?.config ?? explicitSkills?.config ?? [];
if (!Array.isArray(rules)) rules = [];
// Preserve unrelated selectors from effective config and user session flags.
const servers = state?.config?.mcp_servers ?? {};
const shQuote = value => "'" + value.replaceAll("'", "'\\'" + "'") + "'";
const hookCommands = new Set();
let startupHook;
let expectedHookCount = 0;
const sessionHook = context => ['SessionStart', 'SubagentStart'].map(event => {
  const command = (cliOwned&&!mappingUnknown?shQuote(manager)+' __scratch-hook && ':'')+shQuote(process.execPath) + ' -e ' + shQuote('process.stdout.write(' + JSON.stringify(context) + ')');
  hookCommands.add(command);
  if (startupHook) hookCommands.add(startupHook);
  expectedHookCount += startupHook ? 2 : 1;
  return `hooks.${event}=${toml([...(session.hooks?.[event] ?? []),
    // Native SessionStart matches its source. Stable instructions belong to a
    // fresh thread; capability/ownership hooks still run on resume as before.
    ...(startupHook ? [{ ...(event === 'SessionStart' ? { matcher: 'startup' } : {}),
      hooks: [{ type: 'command', timeout: 2, command: startupHook }] }] : []),
    { hooks: [{ type: 'command', timeout: 2, command }] }])}`;
});
async function trustedHooks(selected) {
  const listing = await snapshot(selected, true);
  const handlers = listing.data?.find(entry => entry.cwd === cwd)?.hooks ?? [];
  const owned = handlers.filter(hook => hook.source === 'sessionFlags' && hookCommands.has(hook.command));
  if (owned.length !== expectedHookCount) throw new Error('guidance-hooks-unavailable');
  const trust = { ...(session.hooks?.state ?? {}) };
  for (const hook of owned) trust[hook.key] = { ...trust[hook.key], enabled: true, trusted_hash: hook.currentHash };
  return [...selected, `hooks.state=${toml(trust)}`];
}
// Compose retained capabilities through the native discovery and hook path.
// The outer Serena catalog is connection evidence only. Its backend receives
// effective permissions on the first native tool call, never from this bootstrap.
const serenaName = 'gestalt-serena';
const serenaSkill = state?.skills.find(entry => entry.name === 'gestalt:serena');
const serenaReserved = servers[serenaName];
const serenaConflict = serenaReserved && (serenaReserved.env && Object.keys(serenaReserved.env).length ||
  serenaReserved.enabled === false || serenaReserved.enabled_tools || serenaReserved.disabled_tools?.length ||
  Object.values(serenaReserved.tools ?? {}).some(tool => tool.enabled !== undefined));
const serenaAliases = Object.entries(servers).filter(([name, config]) => name !== serenaName &&
  config.command === manager && config.args?.[0] === 'serena' && config.args?.[1] === 'mcp').map(([name]) => name);
const aliases = serenaAliases.length ? [`mcp_servers=${toml(Object.fromEntries(serenaAliases.map(name => [name, { enabled: false }])))}`] : [];
const capabilities = [{ name: serenaName, skillName: 'gestalt:serena', skill: serenaSkill, valid: false,
    context: '<gestalt_serena_unavailable>\nSerena is unavailable in this runtime. Earlier Serena guidance is inactive; use native code tools.\n</gestalt_serena_unavailable>',
    config: { command: manager, args: ['serena', 'mcp', '--cwd', cwd] } }];
for (const cap of capabilities) cap.inactiveContext = cap.context;
const diagnoseSerena = reason => process.stderr.write(`gestalt: serena unavailable (${reason}); continuing with native code tools\n`);
const usableGuidance = async entry => {
  const path = await realpath(entry.path);
  const manifest = JSON.parse(await readFile(resolve(path, '../../../.codex-plugin/plugin.json'), 'utf8'));
  const nativeVersion = /(?:codex[^0-9]*)?0\.(\d+)\./.exec(state.version);
  if (manifest.name !== 'gestalt' || manifest.skills !== './skills/' || !nativeVersion || Number(nativeVersion[1]) < 160)
    throw new Error('incompatible-runtime');
  return await readFile(path, 'utf8');
};
const common = state && !remote && state.config?.skills?.include_instructions !== false && state.config?.features?.hooks === true;
const startupNotice = reason => process.stderr.write(`gestalt: startup guidance unavailable (${reason}); retaining legacy instructions\n`);
// The selected native skill catalog identifies the installed package. Never
// select a cache version by directory order or consult a source checkout.
async function selectedStartupHook() {
  if (!common) return;
  const nativeVersion = /0\.(\d+)\./.exec(state.version);
  if (!nativeVersion || Number(nativeVersion[1]) < 160) { startupNotice('unsupported-runtime'); return; }
  const selected = state.skills.filter(entry => entry.name.startsWith('gestalt:') && entry.enabled !== false &&
    [...(state.config.skills?.config ?? []), ...rules].filter(rule => rule.name === entry.name || rule.path === entry.path).at(-1)?.enabled !== false);
  if (!selected.length) return;
  try {
    const roots = new Set(await Promise.all(selected.map(async entry => resolve(await realpath(entry.path), '../../..'))));
    if (roots.size !== 1) { startupNotice('ambiguous-selected-package'); return; }
    const packageRoot = [...roots][0];
    const manifest = JSON.parse(await readFile(resolve(packageRoot, '.codex-plugin/plugin.json'), 'utf8'));
    if (manifest.name !== 'gestalt' || manifest.skills !== './skills/') throw Error('invalid-package');
    let descriptor;
    try { descriptor = JSON.parse(await readFile(resolve(packageRoot, 'gestalt-startup-contract.json'), 'utf8')); }
    catch (error) { if (error.code === 'ENOENT') { startupNotice('missing-contract'); return; } throw error; }
    if (descriptor.schemaVersion !== 1 || descriptor.blockVersion !== 1) { startupNotice('unsupported-contract'); return; }
    if (descriptor.composer !== 'scripts/startup-contract.mjs') throw Error('invalid-composer');
    const { pathToFileURL } = await import('node:url');
    const { createHash } = await import('node:crypto');
    const composer = pathToFileURL(resolve(packageRoot, descriptor.composer)).href;
    const { readStartupContract, composeStartup } = await import(composer);
    const contract = await readStartupContract(packageRoot);
    if (contract.status !== 'ready') { startupNotice(contract.reason === 'unsupported-contract' ? 'unsupported-contract' : 'missing-contract'); return; }
    const block = composeStartup('', contract);
    const effective = state.config.developer_instructions ?? '';
    // A scalar owned by native config is immutable through this hook channel.
    // Reuse a current single block there; stale/duplicate blocks need an
    // explicit migration, never an additional hook copy or scalar override.
    const composed = composeStartup(effective, contract);
    const rootNeedsBlock = !effective.includes('<!-- gestalt:startup');
    if (effective.includes('<!-- gestalt:startup')) {
      if (composed !== effective) startupNotice('migration-required');
    }
    // Native standalone role names come from TOML, not filenames. Retain only
    // decisions and fingerprints; never serialize private role instructions.
    // Multiple matching definitions are left to native precedence and omitted
    // from bootstrap delivery with a bounded compatibility diagnostic.
    const { readdir } = await import('node:fs/promises');
    const rolePolicies = Object.create(null);
    const roleFolders = new Set([resolve(environment.CODEX_HOME, 'agents'), ...state.layers
      .filter(layer => layer.name?.type === 'project' && !layer.disabledReason && layer.name.dotCodexFolder)
      .map(layer => resolve(layer.name.dotCodexFolder, 'agents'))]);
    for (const folder of roleFolders) {
      let names;
      try { names = await readdir(folder); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }
      for (const name of names.filter(name => name.endsWith('.toml')).sort()) {
        const path = resolve(folder, name), text = await readFile(path, 'utf8');
        const role = gestaltProfileToml.parse(text);
        if (typeof role.name !== 'string' || typeof role.developer_instructions !== 'string') continue;
        let action = 'append';
        try {
          if (role.developer_instructions.includes('<!-- gestalt:startup'))
            action = composeStartup(role.developer_instructions, contract) === role.developer_instructions ? 'reuse' : 'migration-required';
        } catch { action = 'migration-required'; }
        const policy = { path, digest: createHash('sha256').update(text).digest('hex'), action };
        rolePolicies[role.name] = rolePolicies[role.name] ? { action: 'ambiguous-role' } : policy;
      }
    }
    const digest = createHash('sha256').update(block).digest('hex');
    async function emitStartup(composer, packageRoot, digest, rootNeedsBlock, roles) {
      let reason = 'package-changed';
      try {
        let raw = '';
        for await (const chunk of process.stdin) { raw += chunk; if (raw.length > 16384) throw Error('invalid-hook-input'); }
        const input = JSON.parse(raw);
        if (input.hook_event_name === 'SessionStart' && !rootNeedsBlock) return;
        if (input.hook_event_name === 'SubagentStart') {
          const role = roles[input.agent_type ?? 'default'];
          if (role) {
            if (role.action === 'ambiguous-role') { reason = 'ambiguous-role'; throw Error('ambiguous-role'); }
            reason = 'role-config-changed';
            const { readFile } = await import('node:fs/promises');
            const { createHash } = await import('node:crypto');
            if (!role.path || createHash('sha256').update(await readFile(role.path)).digest('hex') !== role.digest) throw Error('role-config-changed');
            if (role.action === 'reuse') return;
            if (role.action !== 'append') { reason = role.action; throw Error('role-migration'); }
          } else if (!['default', 'worker', 'explorer'].includes(input.agent_type ?? 'default')) {
            reason = 'role-discovery-unavailable'; throw Error('unknown-role');
          } else if (!rootNeedsBlock) return;
        }
        reason = 'package-changed';
        const { readStartupContract, composeStartup } = await import(composer);
        const { createHash } = await import('node:crypto');
        const contract = await readStartupContract(packageRoot);
        if (contract.status !== 'ready') throw Error('package-changed');
        const block = composeStartup('', contract);
        if (createHash('sha256').update(block).digest('hex') !== digest) throw Error('package-changed');
        process.stdout.write(block);
      } catch {
        process.stderr.write(`gestalt: startup guidance unavailable (${reason}); retaining legacy instructions\n`);
      }
    }
    // Only package identity and a digest enter argv. Canonical stable text and
    // effective user instructions are read in-process, never pasted into flags.
    return shQuote(process.execPath) + ' --input-type=module -e ' + shQuote(`(${emitStartup.toString()})(${JSON.stringify(composer)},${JSON.stringify(packageRoot)},${JSON.stringify(digest)},${rootNeedsBlock},${JSON.stringify(rolePolicies)})`);
  } catch { startupNotice('invalid-contract-or-instructions'); }
}
startupHook = await selectedStartupHook();
// Managed browser consent is native named-profile state, independent of
// package installation and of the supervisor's later activation request.
const playwrightName = 'gestalt-playwright';
const playwrightSkill = state?.skills.find(entry => entry.name === 'gestalt:playwright');
const playwrightConfig = servers[playwrightName];
const playwrightConsent = Boolean(namedProfile && playwrightConfig?.enabled === true);
const playwrightRequested = Number(environment.GESTALT_PLAYWRIGHT_READY_TIMEOUT_MS ?? 5000);
const playwrightBudget = Number.isInteger(playwrightRequested) && playwrightRequested >= 100 && playwrightRequested <= 60000 ? playwrightRequested : 5000;
const playwrightRules = [...(state?.config?.skills?.config ?? []), ...rules].filter(rule =>
  rule.name === 'gestalt:playwright' || rule.path === playwrightSkill?.path);
const playwrightNotice = reason => process.stderr.write(`gestalt: playwright unavailable (${reason}); continuing without browser access\n`);
const refreshPlaywrightConsent = async () => {
  try {
    const deadline = Date.now() + playwrightBudget;
    const current = await resolveNamedProfile(await snapshot([], false, false, deadline), deadline, false);
    return Boolean(namedProfile && current?.config?.mcp_servers?.[playwrightName]?.enabled === true);
  } catch { return false; }
};
const playwrightAliases = Object.entries(servers).filter(([name, config]) => name !== playwrightName &&
  config.command === manager && config.args?.[0] === 'playwright' && config.args?.[1] === 'mcp').map(([name]) => name);
if (playwrightAliases.length) aliases.push(`mcp_servers=${toml(Object.fromEntries(playwrightAliases.map(name => [name, { enabled: false }])))}`);

async function managedPlaywright(launchArgs, reportDiagnostic = () => {}, checkConsent = async () => false) {
  // BEGIN MANAGED BROWSER SOCKET ADDRESS
  async function managedBrowserSocket(directory) {
    const fs = await import('node:fs/promises');
    const {constants} = await import('node:fs');
    const {join} = await import('node:path');
    const endpoint = join(directory, 'frontend.sock');
    const capacity = ({linux:108,darwin:104})[process.platform];
    if (!capacity) throw new Error('UNIX_SOCKET_PLATFORM_UNSUPPORTED: no verified pathname capacity for this platform');
    if (Buffer.byteLength(endpoint) + 1 <= capacity)
      return {endpoint, address:endpoint, close:async () => {}};
    if (process.platform !== 'linux')
      throw new Error('UNIX_SOCKET_PATH_TOO_LONG: use a bounded managed runtime root or shorten the endpoint name');
    const handle = await fs.open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
    try {
      const info = await handle.stat();
      if (!info.isDirectory() || (info.mode & 0o777) !== 0o700 ||
          process.getuid && info.uid !== process.getuid() || await fs.realpath(directory) !== directory)
        throw new Error('managed-browser-socket-directory-invalid');
      // Keep the actual socket in its private owner. Linux resolves this short
      // descriptor address to that same directory for bind and native connect.
      const address = `/proc/${process.pid}/fd/${handle.fd}/frontend.sock`;
      if (Buffer.byteLength(address) + 1 > capacity)
        throw new Error('UNIX_SOCKET_PATH_TOO_LONG: shorten the endpoint name');
      const target = await fs.stat(`/proc/${process.pid}/fd/${handle.fd}`);
      if (target.dev !== info.dev || target.ino !== info.ino) throw new Error('managed-browser-socket-directory-changed');
      return {endpoint, address, close:() => handle.close()};
    } catch (error) {await handle.close(); throw error;}
  }
  // END MANAGED BROWSER SOCKET ADDRESS
  const budget = playwrightBudget;
  const fs = await import('node:fs/promises');
  const { createServer } = await import('node:http');
  const { createRequire } = await import('node:module');
  const { join, dirname, basename } = await import('node:path');
  const { randomUUID, createHash } = await import('node:crypto');
  const { tmpdir } = await import('node:os');
  const prefix = `gestalt-${randomUUID()}-`;
  const workspace = await realpath(cwd);
  const launcherOptions = [];
  if (playwrightConfig.args) {
    if (!Array.isArray(playwrightConfig.args) || playwrightConfig.args[0] !== 'playwright' || playwrightConfig.args[1] !== 'mcp')
      throw new Error('launcher-config-conflict');
    for (let i = 2; i < playwrightConfig.args.length; i += 2) {
      const option = playwrightConfig.args[i], value = playwrightConfig.args[i + 1];
      if (typeof value !== 'string') throw new Error('launcher-config-conflict');
      if (option === '--cwd' && await realpath(value) === workspace) continue;
      if (option !== '--executable-path' || !value.startsWith('/') || /[\x00-\x1f\x7f]/.test(value) || launcherOptions.length)
        throw new Error('launcher-config-conflict');
      launcherOptions.push(option, value);
    }
  }
  const packageRoot = await realpath(resolve(environment.GESTALT_HOME, 'playwright'));
  const metadata = JSON.parse(await fs.readFile(join(packageRoot, 'active.json'), 'utf8'));
  const release = await realpath(metadata.release);
  if (metadata.schemaVersion !== 1 || metadata.contractVersion !== 1 || dirname(release) !== packageRoot ||
      !basename(release).startsWith(`release-${metadata.version}-`)) throw new Error('invalid-installation');
  const { ws: WebSocket, wsServer: WebSocketServer } = createRequire(join(release, 'package.json'))('playwright-core/lib/utilsBundle');
  const guidance = await usableGuidance(playwrightSkill);
  const sessionRecords = join(packageRoot, 'cli-sessions');
  await fs.mkdir(sessionRecords, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error; });
  const recordDirectory = await fs.lstat(sessionRecords);
  if (recordDirectory.isSymbolicLink() || !recordDirectory.isDirectory() || await realpath(sessionRecords) !== sessionRecords)
    throw new Error('unsafe-session-record-directory');
  await fs.chmod(sessionRecords, 0o700);
  const rootDir = await fs.mkdtemp(join(tmpdir(), 'gestalt-cli-playwright-'));
  await fs.chmod(rootDir, 0o700);
  let socketAddress;
  let backend, backendGroup, backendLease, frontend, tui, rootThread, rootParameters, nativeBaseline, initializeParams, readinessChild, shutdown = false;
  // Replay the actual composed CLI session configuration into each owned
  // backend. The TUI may send sparse auxiliary overlays, which depend on these
  // valid complete MCP transports (including disabled unrelated capabilities).
  const backendFlags = [];
  for (let i = 0; i < launchArgs.length && launchArgs[i] !== '--'; i++) {
    const arg = launchArgs[i];
    if (arg === '-c' || arg === '--config') backendFlags.push('-c', launchArgs[++i]);
    else if (arg.startsWith('--config=')) backendFlags.push('-c', arg.slice(9));
    else if (arg.startsWith('-c') && arg.length > 2) backendFlags.push('-c', arg.slice(2));
  }
  let desired = false, connected = false, runtimeEnabled = false, controlAvailable = false, pendingBoundary = false, reason = 'idle', activePlan;
  let sequence = 0, serial = Promise.resolve();
  const pending = new Map(), activeTurns = new Set(), plans = new Map();
  const lifecycle = 'gestalt_managed_playwright';
  // Plan IDs are an enumerated host catalog, never caller-provided paths.
  // Binding is root-only and retained in this host session before declarations
  // can request activation. The Org core validates every subsequent read.
  let org;
  try { org = await import(resolve(environment.CODEX_HOME, 'lib/gestalt-org-plan/org-plan-core.mjs')); }
  catch { /* Explicit supervisor requests remain usable without an Org plan. */ }
  const discoverPlans = async () => {
    plans.clear(); if (!org) return;
    try {
      const planDir = await realpath(join(workspace, '.gestalt'));
      if (dirname(planDir) !== workspace) return;
      let inspected = 0;
      for await (const entry of await fs.opendir(planDir)) {
        if (++inspected > 256 || plans.size >= 64) break;
        if (!entry.isFile() || !/^[a-zA-Z0-9_-]{1,64}\.org$/.test(entry.name)) continue;
        const path = await realpath(join(planDir, entry.name));
        if (dirname(path) !== planDir || (await fs.stat(path)).size > 2 * 1024 * 1024) continue;
        try { org.readPlan(path); plans.set(entry.name.slice(0, -4), path); } catch {}
      }
    } catch { /* Missing/invalid plan catalogs do not disable chat. */ }
  };
  const tool = { type: 'function', name: lifecycle,
    description: 'Root supervisor only: request/status/release managed Playwright, or bind a host-cataloged active Org plan ID returned by status. Profile consent is required. Activation may remain pending until an idle owned-runtime resume boundary. No installation.',
    inputSchema: { type: 'object', additionalProperties: false, required: ['action'], properties: {
      action: { type: 'string', enum: ['start', 'status', 'stop', 'bind_plan'] },
      plan: { type: 'string', pattern: '^[a-zA-Z0-9_-]{1,64}$', minLength: 1, maxLength: 64 },
    } } };
  const schemaHash = createHash('sha256').update(JSON.stringify(tool)).digest('hex');
  const workspaceHash = createHash('sha256').update(workspace).digest('hex');
  const nativeVersion = /\b0\.\d+\.\d+\b/.exec(state.version)?.[0];
  const recordPath = id => typeof id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(id) ? join(sessionRecords, id + '.json') : undefined;
  const compatibleSession = async id => {
    const path = recordPath(id); if (!path) return false;
    try {
      const stat = await fs.lstat(path); if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096) return false;
      const record = JSON.parse(await fs.readFile(path, 'utf8'));
      return record.version === 1 && record.threadId === id && record.workspaceHash === workspaceHash &&
        record.schemaHash === schemaHash && record.nativeVersion === nativeVersion;
    } catch { return false; }
  };
  const rememberSession = async id => {
    const path = recordPath(id); if (!path) throw new Error('invalid-thread-id');
    const temporary = join(sessionRecords, '.' + randomUUID() + '.tmp');
    try {
      await fs.writeFile(temporary, JSON.stringify({ version: 1, threadId: id, workspaceHash, schemaHash, nativeVersion }) + '\n', { mode: 0o600, flag: 'wx' });
      await fs.rename(temporary, path);
    } finally { await fs.rm(temporary, { force: true }); }
  };
  const status = () => ({ capability: 'playwright', status: pendingBoundary ? 'pending' : connected ? 'connected' : desired ? 'unavailable' : 'idle',
    reason, availablePlans: [...plans.keys()].slice(0, 16), morePlans: plans.size > 16,
    ...(pendingBoundary ? { boundary: 'owned-runtime-resume' } : {}) });
  const send = message => { if (frontend?.readyState === WebSocket.OPEN) frontend.send(JSON.stringify(message)); };
  const write = message => { if (backend?.stdin.writable) backend.stdin.write(JSON.stringify(message) + '\n'); };
  const request = (method, params) => new Promise((resolve, reject) => {
    const id = prefix + ++sequence;
    const timer = setTimeout(() => { pending.delete(id); reject(new Error('runtime-deadline')); }, budget);
    pending.set(id, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } });
    write({ id, method, params });
  });
  const doctor = async () => {
    const child = spawn(manager, ['playwright', 'doctor', '--json', '--cwd', workspace, ...launcherOptions], {
      cwd: workspace, detached: true, env: Object.fromEntries(['PATH','HOME','TMPDIR','TMP','TEMP','GESTALT_SESSION_TMP_CONTEXT','GESTALT_HOME']
        .filter(key => environment[key] !== undefined).map(key => [key, environment[key]])), stdio: ['ignore', 'pipe', 'ignore'],
    });
    readinessChild = child;
    let output = '', timedOut = false;
    child.stdout.on('data', data => { if (output.length < 32768) output += data; });
    const signal = name => { if (child.pid) try { process.kill(-child.pid, name); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
    let escalation;
    const timer = setTimeout(() => { timedOut = true; signal('SIGTERM'); escalation = setTimeout(() => signal('SIGKILL'), 200); }, budget);
    try {
      const code = await new Promise(resolve => { child.once('error', () => resolve(-1)); child.once('close', resolve); });
      if (code !== 0 || timedOut) return false;
      const value = JSON.parse(output);
      return value.schemaVersion === 1 && value.contractVersion === 1 && value.ready === true &&
        value.package?.ready === true && value.chrome?.ready === true && value.node?.ready === true;
    } catch { return false; }
    finally { clearTimeout(timer); clearTimeout(escalation); signal('SIGKILL'); if (readinessChild === child) readinessChild = undefined; }
  };
  const omitNativeAbsent = value => Array.isArray(value) ? value.map(omitNativeAbsent) : value && typeof value === 'object'
    ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== null).map(([key, item]) => [key, omitNativeAbsent(item)])) : value;
  const serverConfig = enabled => managedToolApproval({ ...omitNativeAbsent(playwrightConfig), command: manager,
    args: ['playwright', 'mcp', '--cwd', workspace, ...launcherOptions], cwd: workspace,
    env_vars: ['GESTALT_HOME',...scratchNames], enabled, required: false, startup_readiness: 'connection', startup_timeout_ms: budget });
  const overlay = (config, enabled = desired) => {
    // Native TUI represents absent config with null, as the protocol permits.
    // A default argument covers undefined only.
    config ??= {};
    const object = value => value && typeof value === 'object' && !Array.isArray(value);
    const mergeOptions = (base, options) => {
      if (!object(options)) return structuredClone(options);
      const result = { ...(object(base) ? base : {}) };
      // An explicit valid transport replacement wins over inherited transport
      // fields. Conflicting transports explicitly supplied together still fail
      // native validation; this adapter does not repair invalid user settings.
      if (Object.hasOwn(options, 'url') && !Object.hasOwn(options, 'command'))
        for (const key of ['command', 'args', 'cwd', 'env', 'env_vars']) delete result[key];
      if (Object.hasOwn(options, 'command') && !Object.hasOwn(options, 'url')) delete result.url;
      for (const [key, value] of Object.entries(options)) Object.defineProperty(result, key, {
        value: object(value) ? mergeOptions(Object.hasOwn(result, key) ? result[key] : {}, value) : structuredClone(value),
        enumerable: true, writable: true, configurable: true,
      });
      return result;
    };
    // Actual native title requests supply whole tables of {enabled:false}
    // entries. Rehydrate their transports from the verified effective baseline,
    // then apply every incoming server option without changing its off state.
    // config/read serializes absent optional fields as null. Native override
    // conversion maps JSON null to an empty TOML string, so those *inherited*
    // absent fields must be omitted; explicit incoming values stay unchanged.
    let servers = mergeOptions(omitNativeAbsent(nativeBaseline?.mcp_servers ?? {}), config.mcp_servers ?? {});
    const options = { ...config }; delete options.mcp_servers;
    for (const key of Object.keys(options).filter(key => key.startsWith('mcp_servers.')).sort()) {
      const path = key.slice('mcp_servers.'.length).split('.');
      let value = options[key];
      for (const part of path.reverse()) value = { [part]: value };
      servers = mergeOptions(servers, value); delete options[key];
    }
    Object.defineProperty(servers, playwrightName, { value: serverConfig(enabled), enumerable: true, configurable: true, writable: true });
    reportDiagnostic('runtime:overlay-timeouts', { message: 'native-config-roundtrip', cause: Object.entries(servers).map(([name, server]) => ({
      name, type: typeof server?.tool_timeout_sec, ...(typeof server?.tool_timeout_sec === 'number' ? { value: server.tool_timeout_sec } : {}),
      nullFields: Object.entries(server ?? {}).filter(([, value]) => value === null).map(([key]) => key),
    })) });
    // Emit one coherent table: no competing whole-table/dotted MCP overrides.
    return managedMcpApprovals({ ...options, mcp_servers: servers,
      'skills.config': [...(config['skills.config'] ?? config.skills?.config ?? state.config?.skills?.config ?? []),
        { name: 'gestalt:playwright', enabled: enabled && connected }] },{manager,codexHome:environment.CODEX_HOME});
  };
  const refreshPlan = () => {
    if (!activePlan) return;
    try {
      const plan = org.readPlan(plans.get(activePlan));
      const milestone = plan.items.find(item => item.level === 1 && item.state === 'WIP');
      const required = milestone?.fields.get('Managed MCP') === 'playwright';
      if (required !== desired) { desired = required; pendingBoundary = true; reason = 'plan-requirement'; }
    } catch {
      activePlan = undefined; desired = false; pendingBoundary = runtimeEnabled; reason = 'plan-unavailable';
    }
  };
  const handleLifecycle = async message => {
    const { threadId, arguments: input } = message.params;
    let result;
    if (!rootThread || threadId !== rootThread || !input || typeof input !== 'object' ||
        Object.keys(input).some(key => !['action', 'plan'].includes(key)) ||
        !tool.inputSchema.properties.action.enum.includes(input.action) ||
        (input.action === 'bind_plan' ? typeof input.plan !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(input.plan) : input.plan !== undefined)) {
      result = { capability: 'playwright', status: 'unavailable', reason: 'root-supervisor-required-or-invalid-request' };
    } else {
      if (!controlAvailable) {
        write({ id: message.id, result: { contentItems: [{ type: 'inputText', text: JSON.stringify({ capability: 'playwright', status: 'unavailable', reason: 'existing-thread-lifecycle-unavailable' }) }], success: true } });
        return;
      }
      if (!await checkConsent()) {
        activePlan = undefined; desired = false; pendingBoundary = runtimeEnabled; reason = 'profile-disabled-or-unavailable';
        write({ id: message.id, result: { contentItems: [{ type: 'inputText', text: JSON.stringify({ ...status(), status: 'unavailable' }) }], success: true } });
        return;
      }
      await discoverPlans();
      if (input.action === 'bind_plan' && !plans.has(input.plan)) {
        write({ id: message.id, result: { contentItems: [{ type: 'inputText', text: JSON.stringify({ capability: 'playwright', status: 'unavailable', reason: 'unknown-plan-id' }) }], success: true } });
        return;
      }
      if (input.action === 'bind_plan') { activePlan = input.plan; refreshPlan(); }
      if (input.action === 'start' || input.action === 'stop') {
        activePlan = undefined;
        desired = input.action === 'start';
        pendingBoundary = desired !== runtimeEnabled;
        reason = pendingBoundary ? 'awaiting-idle-boundary' : desired ? 'verified-tools' : 'released';
      }
      result = status();
    }
    write({ id: message.id, result: { contentItems: [{ type: 'inputText', text: JSON.stringify(result) }], success: true } });
  };
  const stopBackend = async () => {
    const child = backend, group = backendGroup, lease=backendLease;
    backend = undefined; backendGroup = undefined; backendLease=undefined;
    for (const waiter of pending.values()) waiter.reject(new Error('runtime-restarting'));
    pending.clear();
    if (!child) return;
    if(lease){if(await scratchApi.scratchStopped(child,true))scratchApi.scratchRelease(lease);else process.stderr.write('gestalt: browser CLI runtime release unconfirmed; temporary owner remains protected\n');return;}
    const signal = name => { if (group) try { process.kill(-group, name); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
    signal('SIGTERM');
    const timer = setTimeout(() => signal('SIGKILL'), 2000);
    await new Promise(resolve => child.exitCode !== null || child.signalCode !== null ? resolve() : child.once('exit', resolve));
    clearTimeout(timer); signal('SIGKILL');
  };
  const startBackend = () => {
    if(scratchApi)backendLease=scratchApi.scratchBorrow(JSON.parse(environment.GESTALT_SESSION_TMP_CONTEXT),'cli-browser-runtime');
    const child = spawn('codex', ['app-server', '--stdio', ...backendFlags], { cwd: workspace, env: environment,
      detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
    backend = child; backendGroup = child.pid;
    reportDiagnostic('runtime:spawn', { message: 'owned-backend', cause: { pid: child.pid } });
    child.stdin.on('error', () => {});
    child.stderr.on('data', chunk => process.stderr.write(chunk));
    child.on('error', () => { reason = 'runtime-unavailable'; });
    child.on('exit', () => {
      for (const waiter of pending.values()) waiter.reject(new Error('runtime-exited'));
      pending.clear();
      if (backend === child && !shutdown) { connected = false; runtimeEnabled = false; reason = 'runtime-exited'; frontend?.close(1011, 'managed runtime exited'); }
    });
    createInterface({ input: child.stdout }).on('line', line => {
      let message; try { message = JSON.parse(line); } catch { return; }
      const waiter = pending.get(message.id);
      if (waiter) { pending.delete(message.id); message.error ? waiter.reject(new Error('runtime-request-failed', { cause: message.error })) : waiter.resolve(message.result); return; }
      if (message.method === 'item/tool/call' && message.params.tool === lifecycle) {
        handleLifecycle(message).catch(() => { reason = 'invalid-plan-or-request'; write({ id: message.id, result: {
          contentItems: [{ type: 'inputText', text: JSON.stringify({ status: 'unavailable', reason }) }], success: false } }); });
        return;
      }
      const turnKey = message.params?.turn?.id;
      if (message.method === 'turn/started') activeTurns.add(turnKey);
      if (message.method === 'turn/completed') {
        activeTurns.delete(turnKey);
        reportDiagnostic('runtime:turn/completed', { message: message.params.turn.status,
          cause: { threadId: message.params.threadId, turnId: turnKey, active: activeTurns.size } });
      }
      send(message);
    });
  };
  const applyBoundary = async () => {
    if ((desired || connected) && !await checkConsent()) {
      activePlan = undefined; desired = false; pendingBoundary = runtimeEnabled; reason = 'profile-disabled-or-unavailable';
    }
    refreshPlan();
    if (!pendingBoundary || !rootThread) return;
    if (desired && !await doctor()) {
      connected = false; pendingBoundary = false; reason = 'package-or-chrome-unavailable';
      return;
    }
    // Native queued input can reach this frontend before the preceding turn's
    // completion notification. Wait for that observed transition rather than
    // forwarding the next turn with a stale capability configuration.
    const idleDeadline = Date.now() + budget;
    while (activeTurns.size && Date.now() < idleDeadline)
      await new Promise(resolve => setTimeout(resolve, 10));
    if (activeTurns.size) {
      reason = 'active-turns';
      reportDiagnostic('boundary:deferred', { message: reason, cause: { active: activeTurns.size } });
      return;
    }
    // Loaded-thread resume ignores MCP config. Preserve the frontend and the
    // persisted root thread while restarting ONLY this dedicated host runtime.
    const loaded = await request('thread/loaded/list', {});
    for (const id of loaded.data ?? []) {
      const current = await request('thread/read', { threadId: id, includeTurns: false });
      if (current.thread.status?.type === 'active') {
        reason = 'active-threads'; reportDiagnostic('boundary:deferred', { message: reason, cause: { threadId: id } }); return;
      }
    }
    await stopBackend(); connected = false; startBackend();
    reportDiagnostic('boundary:restart', { message: desired ? 'enable' : 'disable' });
    await request('initialize', initializeParams);
    write({ method: 'initialized', params: {} });
    await request('thread/resume', { ...rootParameters, threadId: rootThread, config: overlay(rootParameters?.config, desired) });
    runtimeEnabled = desired;
    if (desired) {
      try {
        const listing = await request('mcpServerStatus/list', { threadId: rootThread, serverName: playwrightName });
        connected = listing.data?.some(server => server.name === playwrightName &&
          ['browser_navigate', 'browser_snapshot', 'browser_take_screenshot'].every(name => server.tools?.[name]));
        reason = connected ? 'verified-tools' : 'connection-or-tools-unavailable';
      } catch { connected = false; reason = 'readiness-timeout-or-unavailable'; }
    } else reason = 'released';
    pendingBoundary = false;
    reportDiagnostic('boundary:ready', { message: reason });
  };
  const forward = async message => {
    let operationHasControl;
    if (message.method === 'initialize') {
      message.params.capabilities = { ...message.params.capabilities, experimentalApi: true };
      initializeParams = message.params;
    }
    if (message.method === 'initialized') {
      write(message);
      nativeBaseline = (await request('config/read', { cwd: workspace, includeLayers: false })).config;
      reportDiagnostic('runtime:baseline-timeouts', { message: 'native-optional-fields', cause: Object.entries(nativeBaseline?.mcp_servers ?? {}).map(([name, server]) => ({
        name, type: typeof server.tool_timeout_sec, absent: server.tool_timeout_sec === null,
        ...(typeof server.tool_timeout_sec === 'number' ? { value: server.tool_timeout_sec } : {}),
      })) });
      return;
    }
    if (['thread/start', 'thread/resume', 'thread/fork'].includes(message.method)) {
      message.params ??= {};
      operationHasControl = message.params.ephemeral !== true &&
        (message.method === 'thread/start' || await compatibleSession(message.params.threadId));
      reportDiagnostic('frontend:' + message.method, { message: message.params.ephemeral === true ? 'auxiliary' : 'persistent',
        cause: { ephemeral: message.params.ephemeral, threadId: message.params.threadId,
          serviceName: message.params.serviceName, threadSource: message.params.threadSource } });
      message.params.config = overlay(message.params.config, false);
      if (message.method === 'thread/start' && operationHasControl)
        message.params.dynamicTools = [...(message.params.dynamicTools ?? []), tool];
    }
    if (message.method === 'turn/start') {
      reportDiagnostic('frontend:turn/start', { message: pendingBoundary ? 'pending' : 'unchanged',
        cause: { threadId: message.params.threadId, active: activeTurns.size } });
      // Native TUI also creates ephemeral auxiliary threads (for example title
      // generation). They never become supervisor roots or activate browsers.
      if (message.params.threadId === rootThread) await applyBoundary();
      if (connected && message.params.threadId === rootThread) {
        message.params.input = [{ type: 'text', text: '<gestalt_playwright_capability>\nVerified managed browser tools are connected. Host MCP approvals apply; shell sandbox roots do not confine this host browser.\n' + guidance + '\n</gestalt_playwright_capability>' }, ...(message.params.input ?? [])];
      } else if (message.params.threadId === rootThread)
        message.params.input = [{ type: 'text', text: controlAvailable
          ? '<gestalt_playwright_unavailable>Browser guidance is inactive. Use gestalt_managed_playwright status; activation requires profile consent and a verified host boundary.</gestalt_playwright_unavailable>'
          : '<gestalt_playwright_unavailable>Managed browser controls cannot be attached to this existing thread by the native runtime. Browser access remains unavailable. Start a fresh opted-in interactive session for managed browser controls; this conversation remains usable.</gestalt_playwright_unavailable>' }, ...(message.params.input ?? [])];
    }
    if (['thread/start', 'thread/resume', 'thread/fork'].includes(message.method)) {
      // Resolve the root from a response to this frontend request, not tool
      // arguments, environment hints, plan text or an executor's identity.
      const result = await request(message.method, message.params);
      reportDiagnostic('runtime:' + message.method, { message: result.thread.ephemeral ? 'auxiliary' : 'persistent',
        cause: { threadId: result.thread.id, ephemeral: result.thread.ephemeral } });
      if (message.params.ephemeral !== true && result.thread.ephemeral !== true) {
        if (rootThread && rootThread !== result.thread.id) {
          desired = false; pendingBoundary = runtimeEnabled; connected = false; activePlan = undefined; reason = 'root-session-changed';
        }
        rootThread = result.thread.id;
        controlAvailable = operationHasControl;
        if (controlAvailable) {
          try { await rememberSession(rootThread); }
          catch { controlAvailable = false; reason = 'session-record-unavailable'; }
        } else {
          reason = 'existing-thread-lifecycle-unavailable';
          process.stderr.write('gestalt: playwright unavailable (existing thread has no compatible managed controls); start a fresh opted-in session for browser access\n');
        }
        // Supported start/resume intersection in the native 0.160 protocol.
        // Preserve effective frontend permissions and settings across restart.
        rootParameters = Object.fromEntries(['approvalPolicy', 'approvalsReviewer', 'baseInstructions', 'config', 'cwd',
          'developerInstructions', 'model', 'modelProvider', 'permissions', 'personality', 'runtimeWorkspaceRoots', 'sandbox', 'serviceTier']
          .filter(key => message.params[key] !== undefined).map(key => [key, structuredClone(message.params[key])]));
      }
      send({ id: message.id, result });
    } else write(message);
  };
  const http = createServer((req, res) => { res.writeHead(404); res.end(); });
  const websocket = new WebSocketServer({ noServer: true, maxPayload: 4 * 1024 * 1024 });
  http.on('upgrade', (req, socket, head) => {
    if (frontend) { socket.destroy(); return; }
    websocket.handleUpgrade(req, socket, head, connection => {
      frontend = connection;
      connection.on('message', data => {
        let message; try { message = JSON.parse(data.toString()); } catch { connection.close(1003); return; }
        // Approval/elicitation responses must keep flowing while a queued user
        // turn waits for idle; otherwise the preceding turn could never finish.
        if (!message.method && message.id !== undefined) { write(message); return; }
        serial = serial.then(() => forward(message)).catch(error => {
          reportDiagnostic(message.method ?? 'response', error);
          if (message.params?.ephemeral !== true) { connected = false; reason = 'runtime-or-boundary-unavailable'; }
          if (message.id !== undefined) send({ id: message.id, error: { code: -32603, message: 'Managed runtime request unavailable; retry or resume the session.' } });
        });
      });
    });
  });
  try {
    socketAddress = await managedBrowserSocket(rootDir);
    startBackend();
    await new Promise((resolve, reject) => { http.once('error', reject); http.listen(socketAddress.address, resolve); });
    await fs.chmod(socketAddress.endpoint, 0o600);
    // User-specified remote endpoints and noninteractive subcommands never
    // enter this dedicated-runtime path. Native arguments remain intact.
    tui = spawn('codex', ['--remote', `unix://${socketAddress.address}`, ...launchArgs], { cwd: process.cwd(), env: environment,
      stdio: [3, 'inherit', 'inherit'] });
    currentChild = tui;
    const code = await new Promise(resolve => { tui.once('error', () => resolve(127)); tui.once('exit', code => resolve(code ?? 143)); });
    return { code, startupFailed: new Set() };
  } finally {
    shutdown = true; currentChild = undefined;
    if (readinessChild?.pid) try { process.kill(-readinessChild.pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
    frontend?.terminate(); websocket.close();
    await new Promise(resolve => http.close(resolve));
    try {await stopBackend();}
    finally {await socketAddress?.close(); await fs.rm(rootDir, { recursive: true, force: true });}
  }
}
const interactivePlaywright = !args.some(arg => ['exec', 'e', 'review', '--no-daemon', '--worktree'].includes(arg)) && !remote;
if (playwrightConsent && interactivePlaywright && playwrightSkill && playwrightRules.at(-1)?.enabled !== false &&
    state.config?.skills?.include_instructions !== false && (!playwrightConfig.command || playwrightConfig.command === manager) &&
    !playwrightConfig.env && !playwrightConfig.env_vars?.length) {
  playwrightController = async launchArgs => {
    try { return await managedPlaywright(launchArgs, undefined, refreshPlaywrightConsent); }
    catch (error) {
      if (error?.message?.startsWith('UNIX_SOCKET_PATH_TOO_LONG'))
        process.stderr.write('gestalt: Unix socket pathname exceeds the platform byte limit; create a new v2 session or shorten the endpoint name.\n');
      if (error?.message?.startsWith('UNIX_SOCKET_PLATFORM_UNSUPPORTED'))
        process.stderr.write('gestalt: no verified Unix socket pathname capacity for this platform.\n');
      playwrightNotice('managed-runtime-unavailable'); playwrightController = undefined;
      return launch(['--no-daemon', ...launchArgs]);
    }
  };
} else if (playwrightConsent) playwrightNotice('unsupported-session-or-skill-config');
// Serena honors native skill exclusions; absence from the selected plugin catalog
// also prevents connection. Do not manufacture a globally installed skill path.
const serenaRules = [...(state?.config?.skills?.config ?? []), ...rules].filter(rule =>
  rule.name === 'gestalt:serena' || rule.path === serenaSkill?.path);
if (common && serenaSkill && serenaSkill.enabled !== false && serenaRules.at(-1)?.enabled !== false && !serenaConflict) {
  try {
    const guidance = await usableGuidance(serenaSkill);
    const install = JSON.parse(await readFile(resolve(environment.GESTALT_HOME, 'serena/active.json'), 'utf8'));
    if (install.schemaVersion !== 1 || install.contractVersion !== 1 || !/^\d+\.\d+\.\d+$/.test(install.version) ||
      !Array.isArray(install.tools) || !['get_symbols_overview', 'find_symbol', 'initial_instructions', 'replace_symbol_body']
        .every(name => install.tools.some(tool => tool.name === name && tool.inputSchema?.type === 'object')))
      throw new Error('invalid-installation');
    for (const executable of [install.executable, install.python, install.uv]) await access(executable, constants.X_OK);
    capabilities[0].valid = true;
    capabilities[0].config = managedToolApproval({ ...serenaReserved, ...capabilities[0].config,
      cwd, env_vars: ['CODEX_HOME','GESTALT_HOME',...scratchNames],
      enabled: true, required: true, startup_readiness: 'connection', startup_timeout_ms: budget });
    capabilities[0].context = '<gestalt_serena_capability>\nSerena is connected to this workspace through a confined, policy-bearing native proxy. '
      + 'A listed catalog does not prove language readiness: first call get_symbols_overview on a current project source file '
      + 'and verify success before relying on semantics or editing. On failure use native code tools. '
      + 'Session and child permissions and approvals apply; plan mode prohibits edits. Do not switch projects or modes.\n'
      + guidance + '\n</gestalt_serena_capability>';
  } catch (error) { diagnoseSerena(error.code === 'ENOENT' ? 'not-installed' : 'invalid-installation-or-plugin'); }
} else if (serenaConflict) diagnoseSerena('session-config-conflict');
if (interrupted) process.exit(interruptionCode);
if (capabilities[0].valid) readinessDeadline = Math.max(readinessDeadline, Date.now() + budget);
const compose = () => {
  hookCommands.clear();
  expectedHookCount = 0;
  const approved = managedMcpApprovals(state?.config ?? {},{manager,codexHome:environment.CODEX_HOME});
  const approvalFlags = [];
  for (const [name,server] of Object.entries(approved.mcp_servers ?? {})) if (isGestaltManagedMcp(name,server,{manager,codexHome:environment.CODEX_HOME})) {
    approvalFlags.push(`mcp_servers.${name}.default_tools_approval_mode="approve"`);
    for (const [tool,options] of Object.entries(server.tools ?? {})) if (options?.approval_mode === 'approve')
      approvalFlags.push(`mcp_servers.${name}.tools.${tool}.approval_mode="approve"`);
  }
  for (const [name,plugin] of Object.entries(approved.plugins ?? {})) if (name === 'context-mode@dyne-gestalt-agents')
    for (const [server,options] of Object.entries(plugin.mcp_servers ?? {})) if (server === 'context-mode') {
      approvalFlags.push(`plugins.${name}.mcp_servers.${server}.default_tools_approval_mode="approve"`);
      for (const [tool,setting] of Object.entries(options.tools ?? {})) if (setting?.approval_mode === 'approve')
        approvalFlags.push(`plugins.${name}.mcp_servers.${server}.tools.${tool}.approval_mode="approve"`);
    }
  const selectors = [...capabilities.flatMap(cap => cap.valid ? [{ name: cap.skillName, enabled: true }] :
    [...(cap.skill ? [{ path: cap.skill.path, enabled: false }] : []), { name: cap.skillName, enabled: false }]),
    { name: 'gestalt:playwright', enabled: false }];
  const deniedSelectors = state || rules.length ? toml([...rules, ...selectors]) :
    rawSkillConfig?.startsWith('[') && rawSkillConfig.endsWith(']')
      ? `${rawSkillConfig.slice(0, -1).replace(/,\s*$/, '')}${rawSkillConfig.slice(1, -1).trim() ? ',' : ''}${toml(selectors).slice(1, -1)}]`
      : toml(selectors);
  const browserOff = { ...playwrightConfig, command: playwrightConfig?.command ?? manager,
    args: playwrightConfig?.args ?? ['playwright', 'mcp', '--cwd', cwd], enabled:false, required:false };
  const browserPolicy = isGestaltManagedMcp(playwrightName,browserOff,{manager,codexHome:environment.CODEX_HOME})
    ? managedToolApproval(browserOff) : browserOff;
  return [...approvalFlags, ...aliases, ...capabilities.map(cap => `mcp_servers.${cap.name}=${toml(cap.valid ? managedToolApproval(cap.config) :
    { command: manager, args: cap.config.args, enabled: false, required: false })}`), `skills.config=${deniedSelectors}`,
    `mcp_servers.${playwrightName}=${toml(browserPolicy)}`,
    ...(state ? sessionHook(capabilities.map(cap => cap.valid ? cap.context : cap.inactiveContext).join('\n')) : [])];
};
async function selection() {
  if(cliOwned&&state?.config?.features?.hooks!==true)protectUnknownMapping();
  let selected = compose();
  try { if (state?.config?.features?.hooks === true) selected = await trustedHooks(selected); }
  catch {
    diagnose('guidance-hooks-unavailable');
    if (startupHook) { startupNotice('guidance-hooks-unavailable'); startupHook = undefined; }
    protectUnknownMapping();
    for (const cap of capabilities) cap.valid = false;
    selected = compose();
  }
  return selected;
}
let result = await launch(appendFlags(await selection()));
// Drop only the failed optional connection, preserving the independent service.
// Retry only the selected retained service after a connection failure.
for (let attempt = 0; result.code !== 0 && !interrupted && attempt < capabilities.length; attempt++) {
  const failed = capabilities.filter(cap => cap.valid && result.startupFailed.has(cap.name));
  if (!failed.length) break;
  for (const cap of failed) {
    cap.valid = false;
    diagnoseSerena('runtime-connection-failed');
  }
  readinessDeadline = Date.now() + budget;
  result = await launch(appendFlags(await selection()));
}
process.exitCode = interrupted ? interruptionCode : result.code;
NODE
}

command_cli() {
  check_node_version
  require_command codex
  strip_separator "$@"
  case ${forwarded_args[0]:-} in
    -h | --help | -V | --version | help | login | logout | plugin | mcp | doctor | features | completion)
      command_cli_owned "${forwarded_args[@]}"
      return ;;
  esac
  if [[ ! ${GESTALT_SESSION_TMP_CONTEXT+x} ]]; then
    resolve_manager_target
    exec_node_program "$(session_scratch_runtime)" cli "$manager_target" "${forwarded_args[@]}"
  fi
  command_cli_owned "${forwarded_args[@]}"
}

command_cli_owned() {
  check_node_version
  require_command codex
  run_startup_diagnostics
  verify_context_mode_installation
  forwarded_args=("$@")
  resolve_manager_target
  log "starting Codex with CODEX_HOME=$codex_home"
  case ${forwarded_args[0]:-} in
    -h | --help | -V | --version | help | login | logout | plugin | mcp | doctor | features | completion)
      exec env CODEX_HOME="$codex_home" GESTALT_HOME="$gestalt_home" \
        GESTALT_STARTUP_DIAGNOSTICS_DONE=1 PATH="$gestalt_home/bin:$codex_home/bin:$PATH" \
        codex "${forwarded_args[@]}" ;;
  esac
  launch_cli_with_capabilities "${forwarded_args[@]}"
}


prepare_codex_approval_launcher() {
  local native_codex native_path='' entry launcher_root
  local -a entries=()
  IFS=: read -r -a entries <<< "$PATH"
  for entry in "${entries[@]}"; do
    # A live update may inherit an older launcher's PATH. Never wrap a wrapper.
    [[ $entry == "$gestalt_home"/run/codex-approval.*/bin ]] && continue
    native_path+=${native_path:+:}${entry:-.}
  done
  native_codex=$(PATH="$native_path" command -v codex) || die 'native Codex executable is missing'
  [[ $native_codex == /* && -x $native_codex ]] || die 'native Codex executable must have an absolute path'
  mkdir -p -- "$gestalt_home/run"
  launcher_root=$(mktemp -d "$gestalt_home/run/codex-approval.XXXXXXXX")
  codex_approval_launcher=$launcher_root/bin
  mkdir -m 700 -- "$codex_approval_launcher"
  # Variables in the generated launcher expand when that launcher runs.
  # shellcheck disable=SC2016
  printf '#!/usr/bin/env bash\nif [[ ${1:-} == app-server ]]; then\n  shift\n  exec %q __codex-app-server %q "$@"\nfi\nexec %q "$@"\n' \
    "$manager_target" "$native_codex" "$native_codex" > "$codex_approval_launcher/codex"
  chmod 0700 "$codex_approval_launcher/codex"
}

# Mobile supplies dynamic MCP tables directly to Codex. Normalize at the final
# host launch boundary, after those tables are composed, not just in config.toml.
command_codex_app_server() {
  local native_codex=${1:-}
  [[ $native_codex == /* && -x $native_codex ]] || die 'native Codex executable is missing'
  shift
  exec node --input-type=module - "${BASH_SOURCE[0]}" "$native_codex" "$@" 3<&0 <<'NODE'
import {createReadStream,fstatSync,readFileSync} from 'node:fs';
import {runInNewContext} from 'node:vm';
import {spawn} from 'node:child_process';
import {Socket} from 'node:net';
import {createInterface} from 'node:readline';
import {randomUUID} from 'node:crypto';
import {createRequire} from 'node:module';
const [manager,native,...args] = process.argv.slice(2);
const policy = readFileSync(manager,'utf8').match(/^\/\/ BEGIN MANAGED MCP APPROVAL POLICY\n([\s\S]*?)^\/\/ END MANAGED MCP APPROVAL POLICY/m);
if (!policy) throw new Error('Managed MCP approval policy missing');
const {managedMcpApprovals,managedMcpOverrides} = runInNewContext(policy[1]+'\n({managedMcpApprovals,managedMcpOverrides})');
const owner = {manager:process.env.GESTALT_MANAGER_BIN ?? manager,codexHome:process.env.CODEX_HOME};
const source = readFileSync(manager,'utf8').match(/^\/\/ BEGIN SESSION SCRATCH RUNTIME\n([\s\S]*?)^\/\/ END SESSION SCRATCH RUNTIME/m);
if (!source) throw new Error('Managed subprocess runtime missing');
const {scratchSpawnProgram} = new Function('require',source[1]+'\nreturn {scratchSpawnProgram};')(createRequire(import.meta.url));
// Keep a live leader until the entire owned group is stopped. Native exit and
// closed output pipes must not cancel escalation for resistant descendants.
const supervisor = `const {spawn}=require('node:child_process');
// Node's stdin-source bootstrap can make inherited stdout nonblocking. Native
// app-server writes must use their own pipe, or large history replies hit EAGAIN.
const child=spawn(process.argv[1],JSON.parse(process.argv[2]),{stdio:['pipe','pipe','inherit']});
child.stdout.pipe(process.stdout);
let ending=false;
function stop(){if(ending)return;ending=true;try{process.kill(-process.pid,'SIGTERM');}catch{}
setTimeout(()=>{try{process.kill(-process.pid,'SIGKILL');}catch{}},750);}
process.on('SIGTERM',stop);process.on('SIGINT',stop);
process.stdin.pipe(child.stdin);process.stdin.on('end',stop);child.stdin.on('error',stop);
child.once('error',()=>{process.send?.({exitCode:127});stop();});
child.once('exit',code=>{process.send?.({exitCode:code??1});stop();});`;
const child = scratchSpawnProgram(supervisor,[native,JSON.stringify(['app-server',...args])],
  {stdio:['pipe','pipe','inherit','ipc'],detached:true,label:'gestalt-codex-lifetime'});
let nativeExitCode;
child.on('message',message=>{if(Number.isInteger(message?.exitCode))nativeExitCode=message.exitCode;});
const pending = new Map(),reads = new Set(),prefix = 'gestalt-approvals-'+randomUUID()+'-';
let sequence = 0,closing = false;
const write = message => child.stdin.write(JSON.stringify(message)+'\n');
const send = message => process.stdout.write(JSON.stringify(message)+'\n');
const request = params => new Promise((resolve,reject) => {
  const id = prefix+(++sequence),timer = setTimeout(()=>{pending.delete(id);reject(Error('config-timeout'));},5000);
  pending.set(id,{resolve:value=>{clearTimeout(timer);resolve(value);},reject:error=>{clearTimeout(timer);reject(error);}});
  write({id,method:'config/read',params});
});
const output = createInterface({input:child.stdout});
output.on('line',line=>{
  let message;try {message=JSON.parse(line);}catch {return stop(1);}
  const waiter=pending.get(message.id);
  if(waiter){pending.delete(message.id);message.error?waiter.reject(Error('config-unavailable')):waiter.resolve(message.result);return;}
  if((message.result || message.error) && reads.delete(message.id) && message.result?.config)
    message.result={...message.result,config:managedMcpApprovals(message.result.config,owner)};
  send(message);
});
// fs.ReadStream queues a blocking read on this pipe. Even process.exit() can
// then wait forever for its worker while Mobile keeps the write end open.
const inputType = fstatSync(3);
const inputStream = inputType.isFIFO() || inputType.isSocket()
  ? new Socket({fd:3,readable:true,writable:false}) : createReadStream(null,{fd:3});
const input = createInterface({input:inputStream});
input.on('line',async line=>{
  let message;try {message=JSON.parse(line);}catch {return stop(1);}
  try {
    if(['thread/start','thread/resume','thread/fork'].includes(message.method)) {
      const baseline=await request({includeLayers:false,...(message.params?.cwd?{cwd:message.params.cwd}:{})});
      message.params={...message.params,config:managedMcpOverrides(message.params?.config??{},baseline.config??{},owner)};
    }
    if(message.method==='config/read' && message.id!==undefined)reads.add(message.id);
    write(message);
  }catch {
    if(message.id!==undefined)send({id:message.id,error:{code:-32603,message:'Could not prepare managed MCP approval policy'}});
  }
});
function signal(name){if(child.pid&&child.exitCode===null&&child.signalCode===null)try{process.kill(-child.pid,name);}catch(error){if(error.code!=='ESRCH')throw error;}}
function stop(code=0){if(closing)return;closing=true;input.close();inputStream.destroy();child.stdin.end();signal('SIGTERM');
  // Bound the proxy too: descendants may retain stdout after the native child
  // exits, so waiting for ChildProcess.close alone is not a shutdown deadline.
  const timer=setTimeout(()=>{signal('SIGKILL');process.exit(code);},2000);
  child.once('close',()=>{clearTimeout(timer);process.exit(code);});}
input.on('close',()=>stop());inputStream.on('error',()=>stop(1));child.stdin.on('error',()=>stop(1));
child.on('error',()=>{inputStream.destroy();process.exit(1);});
child.on('exit',code=>{if(!closing)stop(nativeExitCode??code??1);});
child.on('close',code=>{for(const waiter of pending.values())waiter.reject(Error('runtime-exited'));if(!closing)process.exit(nativeExitCode??code??1);});
process.on('SIGTERM',()=>stop(143));process.on('SIGINT',()=>stop(130));
NODE
}

command_mobile() {
  local mobile_restart_dir mobile_restart_state mobile_restart_staged restart_cwd
  local context_mode_runtime context_mode_plugin_root gestalt_plugin_root
  local plugin_inventory='' gestalt_agents_version='' context_mode_version=''
  local mobile_workspace=$PWD mobile_arg_index

  strip_separator "$@"
  # Reject obsolete manually supplied options before installation or startup.
  # Stored descriptors are adapted separately by the explicit restart worker.
  for ((mobile_arg_index = 0; mobile_arg_index < ${#forwarded_args[@]}; mobile_arg_index++)); do
    case ${forwarded_args[mobile_arg_index]} in
      --xerj | --xerj=*) die 'Xerj has been retired; omit --xerj when starting Mobile. Run gestalt update before restarting older generated launchers.' ;;
    esac
  done
  if [[ ! -x $mobile_bin ]]; then
    log 'Gestalt Mobile is not installed; installing it now'
    install_mobile
  fi
  for ((mobile_arg_index = 0; mobile_arg_index < ${#forwarded_args[@]}; mobile_arg_index++)); do
    if [[ ${forwarded_args[mobile_arg_index]} == --cwd && -d ${forwarded_args[mobile_arg_index+1]:-} ]]; then
      mobile_workspace=${forwarded_args[mobile_arg_index+1]}
    fi
  done
  run_startup_diagnostics --cwd "$mobile_workspace"
  plugin_inventory=$(CODEX_HOME=$codex_home codex plugin list \
    --marketplace "$marketplace_name" --json 2>/dev/null) || plugin_inventory=''
  if [[ -n $plugin_inventory ]]; then
    gestalt_agents_version=$(printf '%s' "$plugin_inventory" | read_plugin_version gestalt) ||
      gestalt_agents_version=''
    context_mode_version=$(printf '%s' "$plugin_inventory" | read_plugin_version context-mode) ||
      context_mode_version=''
  fi
  context_mode_runtime=''
  context_mode_plugin_root=''
  gestalt_plugin_root=''
  if [[ -n $context_mode_version ]]; then
    context_mode_runtime=$(context_mode_runtime_root "$context_mode_version") ||
      log 'could not resolve the context-mode runtime path for executor discovery'
    context_mode_plugin_root=$codex_home/plugins/cache/$marketplace_name/context-mode/$context_mode_version
  fi
  if [[ -n $gestalt_agents_version ]]; then
    gestalt_plugin_root=$codex_home/plugins/cache/$marketplace_name/gestalt/$gestalt_agents_version
  fi
  mobile_restart_dir=$gestalt_home/run
  mobile_restart_state=$mobile_restart_dir/mobile-$$.restart
  mkdir -p -- "$mobile_restart_dir"
  mobile_restart_staged=$(mktemp "$mobile_restart_dir/.mobile-$$.XXXXXXXX") ||
    die 'could not stage the Mobile restart descriptor'
  restart_cwd=$(pwd -P) || die 'could not resolve the Mobile working directory'
  {
    printf '%s\0' "$restart_cwd"
    if ((${#forwarded_args[@]} > 0)); then
      printf '%s\0' "${forwarded_args[@]}"
    fi
  } > "$mobile_restart_staged"
  chmod 0600 "$mobile_restart_staged"
  mv -f -- "$mobile_restart_staged" "$mobile_restart_state"
  resolve_manager_target
  log "starting Gestalt Mobile from $mobile_root"
  prepare_codex_approval_launcher
  exec env CODEX_HOME="$codex_home" GESTALT_HOME="$gestalt_home" \
    GESTALT_MANAGER_BIN="$manager_target" \
    GESTALT_MANAGER_VERSION="$GESTALT_CLI_VERSION" \
    GESTALT_AGENTS_VERSION="$gestalt_agents_version" \
    GESTALT_AGENTS_PLUGIN_ROOT="$gestalt_plugin_root" \
    GESTALT_CONTEXT_MODE_VERSION="$context_mode_version" \
    GESTALT_SERENA_VERSION="$(serena_versions serena 2>/dev/null || true)" \
    GESTALT_UV_VERSION="$(serena_versions uv 2>/dev/null || true)" \
    GESTALT_SERENA_PYTHON_VERSION="$(serena_versions python 2>/dev/null || true)" \
    GESTALT_CONTEXT_MODE_PLUGIN_ROOT="$context_mode_plugin_root" \
    GESTALT_CONTEXT_MODE_RUNTIME="$context_mode_runtime" \
    GESTALT_MOBILE_BIN="$mobile_bin" \
    GESTALT_MOBILE_PID="$$" \
    GESTALT_MOBILE_RESTART_STATE="$mobile_restart_state" \
    GESTALT_STARTUP_DIAGNOSTICS_DONE=1 \
    PATH="$codex_approval_launcher:$gestalt_home/bin:$codex_home/bin:$PATH" \
    "$mobile_bin" "${forwarded_args[@]}"
}

print_check() {
  local -r label=$1
  local -r status=$2
  printf '%-24s %s\n' "$label" "$status"
}

command_version() {
  local value plugin
  printf 'gestalt %s\n' "$GESTALT_CLI_VERSION"
  if [[ -x $mobile_bin ]]; then
    value=$("$mobile_bin" --version 2>/dev/null) && print_check 'Gestalt Mobile' "$value"
  fi
  for plugin in gestalt context-mode; do
    value=$(CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
      read_plugin_version "$plugin" 2>/dev/null) || continue
    print_check "$plugin" "$value"
  done
  if command -v codex >/dev/null 2>&1; then
    value=$(codex --version 2>/dev/null) && print_check 'Codex CLI' "$value"
  fi
  if command -v kimi >/dev/null 2>&1; then
    value=$(kimi --version 2>/dev/null) && print_check 'Kimi CLI' "$value"
  fi
  value=$(serena_versions serena 2>/dev/null || true)
  print_check 'Serena' "${value:-NOT INSTALLED (optional)}"
  value=$(command_playwright version 2>/dev/null || true)
  print_check 'Playwright' "${value:-NOT INSTALLED (optional)}"
  value=$(command_playwright doctor 2>/dev/null || true)
  print_check 'Playwright readiness' "$value"
  value=$(serena_versions uv 2>/dev/null || true)
  print_check 'uv (Serena)' "${value:-NOT INSTALLED (optional)}"
  value=$(serena_versions python 2>/dev/null || true)
  print_check 'Python (Serena)' "${value:-NOT INSTALLED (optional)}"
  return 0
}

read_plugin_version() {
  local -r plugin_name=$1
  # shellcheck disable=SC2016 # The Node program intentionally owns its JavaScript interpolation.
  node -e '
    let input = "";
    const pluginName = process.argv[1];
    process.stdin.setEncoding("utf8");
    process.stdin.on("data", chunk => { input += chunk; });
    process.stdin.on("end", () => {
      const result = JSON.parse(input);
      const installed = Array.isArray(result) ? result : result.installed;
      const plugin = Array.isArray(installed)
        ? installed.find(candidate =>
            candidate && candidate.name === pluginName && candidate.installed !== false)
        : undefined;
      if (!plugin || typeof plugin.version !== "string" || plugin.version.length === 0) {
        process.exitCode = 1;
        return;
      }
      process.stdout.write(plugin.version);
    });
  ' "$plugin_name"
}

context_mode_plugin_source_is_disabled() {
  CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
    node -e '
      let input = "";
      process.stdin.setEncoding("utf8");
      process.stdin.on("data", chunk => { input += chunk; });
      process.stdin.on("end", () => {
        const result = JSON.parse(input);
        const installed = Array.isArray(result) ? result : result.installed;
        const plugin = Array.isArray(installed)
          ? installed.find(candidate => candidate && candidate.name === "context-mode")
          : undefined;
        if (!plugin || plugin.installed === false || plugin.enabled !== false) process.exitCode = 1;
      });
    '
}

context_mode_native_mcp_is_enabled() {
  local -r expected_launcher=$codex_home/bin/context-mode-mcp.mjs

  CODEX_HOME=$codex_home codex mcp get context-mode --json 2>/dev/null |
    node -e '
      let input = "";
      const expectedLauncher = process.argv[1];
      process.stdin.setEncoding("utf8");
      process.stdin.on("data", chunk => { input += chunk; });
      process.stdin.on("end", () => {
        const server = JSON.parse(input);
        const command = server.transport?.command ?? server.command;
        const args = server.transport?.args ?? server.args;
        if (server.enabled !== true || command !== "node" ||
            !Array.isArray(args) || args.length !== 1 || args[0] !== expectedLauncher) {
          process.exitCode = 1;
        }
      });
    ' "$expected_launcher"
}

context_mode_runtime_root() {
  # Older marketplace releases still prepare a versioned tree. Keep discovery
  # compatible until their next setup migrates it to the single runtime.
  if [[ ! -f $gestalt_home/runtime/context-mode/.context-mode-prepared.json ]]; then
    local runtime_identity legacy
    runtime_identity=$(node -p '[process.platform, process.arch, "node-" + process.versions.modules].join("-")') || return 1
    legacy=$gestalt_home/runtime/context-mode/$1/$runtime_identity
    if [[ -f $legacy/.context-mode-prepared.json ]]; then
      printf '%s\n' "$legacy"
      return
    fi
  fi
  printf '%s/runtime/context-mode\n' "$gestalt_home"
}

installed_plugin_version() {
  local -r plugin_name=$1
  local inherited_version=''

  case $plugin_name in
    gestalt) inherited_version=${GESTALT_AGENTS_VERSION:-} ;;
    context-mode) inherited_version=${GESTALT_CONTEXT_MODE_VERSION:-} ;;
    *) die "unsupported plugin path: $plugin_name" ;;
  esac
  if [[ -n $inherited_version ]]; then
    printf '%s\n' "$inherited_version"
    return 0
  fi
  command -v codex >/dev/null 2>&1 ||
    die "cannot resolve $plugin_name: codex is not available and no session version was exported"
  CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
    read_plugin_version "$plugin_name" ||
    die "cannot resolve the installed $plugin_name plugin version"
}

managed_path() {
  local -r name=$1
  local version

  case $name in
    bin) printf '%s/bin\n' "$gestalt_home" ;;
    org-plan | context-mode-cli) printf '%s/bin/%s\n' "$gestalt_home" "${name%-cli}" ;;
    mobile) printf '%s\n' "${GESTALT_MOBILE_BIN:-$mobile_bin}" ;;
    context-mode | context-mode-runtime)
      if [[ -n ${GESTALT_CONTEXT_MODE_RUNTIME:-} ]]; then
        printf '%s\n' "$GESTALT_CONTEXT_MODE_RUNTIME"
      else
        version=$(installed_plugin_version context-mode)
        context_mode_runtime_root "$version"
      fi
      ;;
    context-mode-plugin)
      if [[ -n ${GESTALT_CONTEXT_MODE_PLUGIN_ROOT:-} ]]; then
        printf '%s\n' "$GESTALT_CONTEXT_MODE_PLUGIN_ROOT"
      else
        version=$(installed_plugin_version context-mode)
        printf '%s/plugins/cache/%s/context-mode/%s\n' "$codex_home" "$marketplace_name" "$version"
      fi
      ;;
    gestalt-plugin)
      if [[ -n ${GESTALT_AGENTS_PLUGIN_ROOT:-} ]]; then
        printf '%s\n' "$GESTALT_AGENTS_PLUGIN_ROOT"
      else
        version=$(installed_plugin_version gestalt)
        printf '%s/plugins/cache/%s/gestalt/%s\n' "$codex_home" "$marketplace_name" "$version"
      fi
      ;;
    codex-home) printf '%s\n' "$codex_home" ;;
    gestalt-home) printf '%s\n' "$gestalt_home" ;;
    *)
      die "unknown managed path: $name (expected bin, org-plan, context-mode-cli, mobile, context-mode, context-mode-plugin, gestalt-plugin, codex-home, or gestalt-home)"
      ;;
  esac
}

command_path() {
  local name mobile_path context_runtime context_plugin gestalt_plugin

  if (($# == 1)) && [[ $1 != --json ]]; then
    managed_path "$1"
    return
  fi
  (($# == 0)) || { (($# == 1)) && [[ $1 == --json ]]; } ||
    die 'usage: gestalt path [NAME|--json]'

  mobile_path=$(managed_path mobile)
  context_runtime=$(managed_path context-mode)
  context_plugin=$(managed_path context-mode-plugin)
  gestalt_plugin=$(managed_path gestalt-plugin)
  if (($# == 1)); then
    # shellcheck disable=SC2016 # The Node program intentionally owns its JavaScript interpolation.
    node -e '
      const [mobile, contextModeRuntime, contextModePlugin, gestaltPlugin, codexHome, gestaltHome] =
        process.argv.slice(1);
      process.stdout.write(`${JSON.stringify({
        mobile,
        contextModeRuntime,
        contextModePlugin,
        gestaltPlugin,
        codexHome,
        gestaltHome,
        bin: `${gestaltHome}/bin`,
        contextModeCli: `${gestaltHome}/bin/context-mode`,
        orgPlan: `${gestaltHome}/bin/org-plan`,
      })}\n`);
    ' "$mobile_path" "$context_runtime" "$context_plugin" "$gestalt_plugin" "$codex_home" "$gestalt_home"
    return
  fi
  print_check 'Gestalt Mobile' "$mobile_path"
  print_check 'Gestalt commands' "$gestalt_home/bin"
  print_check 'Context-mode runtime' "$context_runtime"
  print_check 'Context-mode plugin' "$context_plugin"
  print_check 'Gestalt plugin' "$gestalt_plugin"
  print_check 'Codex home' "$codex_home"
  print_check 'Gestalt home' "$gestalt_home"
}

context_mode_runtime_is_prepared() {
  local -r version=$1
  local runtime_root marker
  runtime_root=$(context_mode_runtime_root "$version") || return 1
  marker=$runtime_root/.context-mode-prepared.json
  [[ -f $marker && -f $runtime_root/cli.bundle.mjs && -f $runtime_root/server.bundle.mjs ]] ||
    return 1
  node -e '
    const fs = require("node:fs");
    const marker = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
    if (marker.packageVersion !== process.argv[2] ||
        marker.nodeModulesAbi !== process.versions.modules ||
        marker.platform !== process.platform || marker.arch !== process.arch) process.exit(1);
  ' "$marker" "$version"
}

read_supervision_capabilities() {
  local -r component=$1
  local -r manifest=$2

  if [[ ! -f $manifest ]]; then
    printf 'UNAVAILABLE'
    return 0
  fi
  if [[ ! -r $manifest || $(wc -c < "$manifest") -gt 16384 ]]; then
    printf 'MALFORMED'
    return 0
  fi

  # shellcheck disable=SC2016 # The Node program intentionally owns its JavaScript interpolation.
  node -e '
    const fs = require("node:fs");
    const [file, component, schema] = process.argv.slice(1);
    try {
      const value = JSON.parse(fs.readFileSync(file, "utf8"));
      const capabilities = value.capabilities;
      if (!value || typeof value !== "object" || Array.isArray(value) ||
          value.schemaVersion !== Number(schema) || value.component !== component ||
          !Number.isInteger(value.supervisionContract) ||
          !Array.isArray(capabilities) ||
          capabilities.some(capability => typeof capability !== "string" ||
            !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability))) {
        process.stdout.write("MALFORMED");
      } else {
        const policy = value.modelPolicyContract;
        const declared = capabilities.some(name => name.startsWith("l1-model-policy-"));
        if (declared !== (policy !== undefined) || (declared &&
            (!policy || typeof policy !== "object" || Array.isArray(policy) ||
             !Number.isInteger(policy.version) || typeof policy.scope !== "string" ||
             !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(policy.scope) ||
             typeof policy.runtimeEnforcement !== "boolean" ||
             (policy.scope === "configured-launch-and-retention" &&
              (policy.defaultAssurance !== "configured" || policy.strictAttestation !== false))))) {
          process.stdout.write("MALFORMED");
        } else {
          const model = declared ? `${policy.version}:${policy.scope}:${policy.runtimeEnforcement}` : "legacy";
          process.stdout.write(`READY|${value.supervisionContract}|${[...new Set(capabilities)].sort().join(",")}|${model}`);
        }
      }
    } catch {
      process.stdout.write("MALFORMED");
    }
  ' "$manifest" "$component" "$SUPERVISION_CAPABILITY_SCHEMA"
}

has_supervision_capability() {
  local -r capabilities=$1
  local -r expected=$2
  [[ ,$capabilities, == *",$expected,"* ]]
}

check_supervision_capability_coherence() {
  local agents mobile agents_contract agents_capabilities mobile_contract mobile_capabilities
  local capability agents_model mobile_model
  local -a agents_required=(supervision-start wait-lease-tool checkpoint-tool agent-capacity-recovery canonical-agent-identity org-plan-contract)
  local -a mobile_required=(supervision-start wait-lease-tool checkpoint-tool agent-capacity-recovery controller-status canonical-agent-identity session-verdict acknowledgement-safe-composer org-plan-contract)

  agents=$(read_supervision_capabilities agents "$agents_capability_manifest")
  mobile=$(read_supervision_capabilities mobile "$mobile_capability_manifest")
  if [[ $agents == UNAVAILABLE ]]; then
    print_check 'Agents supervision' 'UNAVAILABLE (run gestalt update, then restart Mobile)'
    return 1
  fi
  if [[ $mobile == UNAVAILABLE ]]; then
    print_check 'Mobile supervision' 'UNAVAILABLE (run gestalt update, then restart Mobile)'
    return 1
  fi
  if [[ $agents == MALFORMED ]]; then
    print_check 'Agents supervision' 'INCOMPATIBLE (malformed capability manifest; run gestalt update, then restart Mobile)'
    return 1
  fi
  if [[ $mobile == MALFORMED ]]; then
    print_check 'Mobile supervision' 'INCOMPATIBLE (malformed capability manifest; run gestalt update, then restart Mobile)'
    return 1
  fi

  IFS='|' read -r _ agents_contract agents_capabilities agents_model <<< "$agents"
  IFS='|' read -r _ mobile_contract mobile_capabilities mobile_model <<< "$mobile"
  if [[ $agents_contract != "$SUPERVISION_CONTRACT_VERSION" || $mobile_contract != "$SUPERVISION_CONTRACT_VERSION" || $agents_contract != "$mobile_contract" ]]; then
    print_check 'Supervision contract' "INCOMPATIBLE (Agents=$agents_contract Mobile=$mobile_contract; run gestalt update, then restart Mobile)"
    return 1
  fi
  for capability in "${agents_required[@]}"; do
    if ! has_supervision_capability "$agents_capabilities" "$capability"; then
      print_check 'Agents supervision' "INCOMPATIBLE (missing $capability; run gestalt update, then restart Mobile)"
      return 1
    fi
  done
  for capability in "${mobile_required[@]}"; do
    if ! has_supervision_capability "$mobile_capabilities" "$capability"; then
      print_check 'Mobile supervision' "INCOMPATIBLE (missing $capability; run gestalt update, then restart Mobile)"
      return 1
    fi
  done
  print_check 'Supervision contract' "ready (v$agents_contract; offline manifests)"
  if [[ $agents_model == legacy && $mobile_model == legacy ]]; then
    print_check 'L1 model policy' 'LEGACY (base supervision only; update both packages for configured-policy diagnostics)'
    return 0
  fi
  if [[ $agents_model == 1:configured-launch-and-retention:false &&
        $mobile_model == 1:configured-launch-and-retention:false ]] &&
      has_supervision_capability "$agents_capabilities" l1-model-policy-v1 &&
      has_supervision_capability "$mobile_capabilities" l1-model-policy-v1 &&
      has_supervision_capability "$agents_capabilities" l2-report-boundary &&
      has_supervision_capability "$mobile_capabilities" l2-report-boundary; then
    print_check 'L1 model policy' 'SUPPORTED (v1 configured compatibility; explicit strict attestation unsupported; runtimeEnforcement=false)'
    return 0
  fi
  if [[ $agents_model != 1:schema-and-local-contracts:false ||
        $mobile_model != 1:schema-and-retention:false ]] ||
      ! has_supervision_capability "$agents_capabilities" l1-model-policy-v1 ||
      ! has_supervision_capability "$mobile_capabilities" l1-model-policy-v1 ||
      ! has_supervision_capability "$agents_capabilities" l2-report-boundary ||
      ! has_supervision_capability "$mobile_capabilities" l2-report-boundary; then
    print_check 'L1 model policy' 'INCOMPATIBLE (update or roll back Agents and Mobile together; then restart Mobile)'
    return 1
  fi
  print_check 'L1 model policy' 'SUPPORTED (v1 schema/configuration diagnostics; runtimeEnforcement=false; automatic policy launches unsupported)'
}

verify_context_mode_installation() {
  local gestalt_version context_version runtime_root
  gestalt_version=$(
    CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
      read_plugin_version gestalt
  ) || die 'Gestalt plugin is not installed after marketplace setup'
  context_version=$(
    CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
      read_plugin_version context-mode
  ) || die 'context-mode plugin is not installed after marketplace setup'
  [[ $context_version == "$gestalt_version" ]] ||
    die "plugin version skew after marketplace setup: gestalt=$gestalt_version context-mode=$context_version"
  runtime_root=$(context_mode_runtime_root "$context_version") ||
    die 'could not resolve the context-mode runtime path'
  context_mode_runtime_is_prepared "$context_version" ||
    die "context-mode $context_version runtime is not prepared: $runtime_root"
  context_mode_plugin_source_is_disabled ||
    die 'context-mode plugin source must remain disabled; run gestalt install or gestalt update to restore the native MCP bridge'
  context_mode_native_mcp_is_enabled ||
    die 'context-mode native MCP bridge is missing or disabled; run gestalt install or gestalt update'
  log "verified context-mode $context_version plugin and external runtime"
}

run_doctor_command() {
  local -r label=$1
  shift
  printf '\n%s\n' "$label"
  if "$@"; then
    return 0
  fi
  log "$label reported a problem"
  return 1
}

run_startup_diagnostics() {
  log 'running startup diagnostics'
  if ! command_doctor "$@"; then
    log 'startup diagnostics reported a problem; launch will continue after required runtime checks'
  fi
}

run_codex_doctor() {
  # Session scratch forwarding is required for session launches, but is optional
  # for an operator's read-only diagnostics. Do not invent an owner or edit config.
  CODEX_HOME="$codex_home" node --input-type=module - "${BASH_SOURCE[0]}" <<'NODE'
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { spawn } from 'node:child_process';
const args = ['doctor', '--summary', '--ascii', '--no-color'];
const scratch = new Set(['GESTALT_SESSION_TMP_CONTEXT', 'TMPDIR', 'TMP', 'TEMP']);
try {
  const source = readFileSync(process.argv[2], 'utf8');
  const bundle = source.match(/^\/\/ BEGIN BUNDLED PROFILE TOML PARSER\n([\s\S]*?)^\/\/ END BUNDLED PROFILE TOML PARSER/m);
  const { parse } = runInNewContext(bundle[1] + '\ngestaltProfileToml');
  const config = parse(readFileSync(process.env.CODEX_HOME + '/config.toml', 'utf8'));
  const policy = source.match(/^\/\/ BEGIN MANAGED MCP APPROVAL POLICY\n([\s\S]*?)^\/\/ END MANAGED MCP APPROVAL POLICY/m);
  const { isGestaltManagedMcp } = runInNewContext(policy[1] + '\n({isGestaltManagedMcp})');
  for (const [name, server] of Object.entries(config.mcp_servers ?? {})) {
    if (!isGestaltManagedMcp(name, server, {manager: process.argv[2], codexHome: process.env.CODEX_HOME})) continue;
    const names = server.env_vars ?? [];
    const retained = names.filter(key => !scratch.has(key) || Object.hasOwn(process.env, key));
    if (retained.length !== names.length)
      args.push('-c', 'mcp_servers.' + name + '.env_vars=' + JSON.stringify(retained));
  }
} catch { /* Native doctor owns reporting missing or malformed configuration. */ }
const child = spawn('codex', args, {stdio: ['ignore', 'inherit', 'inherit']});
child.once('error', () => {process.exitCode = 1;});
child.once('close', code => {process.exitCode = code ?? 1;});
NODE
}

command_doctor() {
  local failed=false node_version codex_version gestalt_plugin_version
  local context_mode_plugin_version context_mode_runtime mobile_version_output
  local workspace=$PWD
  if (($#)); then
    [[ $# == 2 && $1 == --cwd && -d $2 ]] || die 'usage: gestalt doctor [--cwd ROOT]'
    workspace=$2
  fi

  printf 'Gestalt manager %s\n\n' "$GESTALT_CLI_VERSION"
  print_check 'Codex home' "$codex_home"
  print_check 'Gestalt home' "$gestalt_home"

  if command -v node >/dev/null 2>&1; then
    node_version=$(node -p 'process.versions.node' 2>/dev/null || printf 'unreadable')
    print_check 'Node.js' "$node_version"
    [[ ${node_version%%.*} =~ ^[0-9]+$ ]] && (( ${node_version%%.*} >= 24 )) || failed=true
  else
    print_check 'Node.js' 'MISSING (24+ required)'
    failed=true
  fi

  if command -v npm >/dev/null 2>&1; then
    print_check 'npm' "$(npm --version 2>/dev/null || printf 'unreadable')"
  else
    print_check 'npm' 'MISSING'
    failed=true
  fi

  if command -v codex >/dev/null 2>&1; then
    codex_version=$(codex --version 2>/dev/null || printf 'unreadable')
    print_check 'Codex CLI' "$codex_version"
  else
    print_check 'Codex CLI' 'MISSING'
    failed=true
  fi

  if [[ -f $marketplace_setup ]]; then
    print_check 'Agents marketplace' 'present'
  else
    print_check 'Agents marketplace' 'MISSING'
    failed=true
  fi

  if command -v codex >/dev/null 2>&1 && [[ -d $codex_home ]]; then
    if gestalt_plugin_version=$(
      CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
        read_plugin_version gestalt 2>/dev/null
    ); then
      print_check 'Gestalt plugins' "$gestalt_plugin_version"
    else
      print_check 'Gestalt plugins' 'NOT VERIFIED'
      failed=true
    fi
    if context_mode_plugin_version=$(
      CODEX_HOME=$codex_home codex plugin list --marketplace "$marketplace_name" --json 2>/dev/null |
        read_plugin_version context-mode 2>/dev/null
    ); then
      print_check 'Context-mode plugin' "$context_mode_plugin_version"
      if [[ -n ${gestalt_plugin_version:-} &&
            $context_mode_plugin_version != "$gestalt_plugin_version" ]]; then
        print_check 'Plugin version match' \
          "MISMATCH (gestalt=$gestalt_plugin_version context-mode=$context_mode_plugin_version)"
        failed=true
      elif context_mode_runtime_is_prepared "$context_mode_plugin_version"; then
        context_mode_runtime=$(context_mode_runtime_root "$context_mode_plugin_version")
        print_check 'Context-mode runtime' "$context_mode_runtime"
      else
        context_mode_runtime=$(context_mode_runtime_root "$context_mode_plugin_version" || printf 'unresolved')
        print_check 'Context-mode runtime' "NOT PREPARED ($context_mode_runtime)"
        failed=true
      fi
      if context_mode_plugin_source_is_disabled; then
        print_check 'Plugin MCP source' 'disabled (expected)'
      else
        print_check 'Plugin MCP source' 'ENABLED (disable it; native bridge owns startup)'
        failed=true
      fi
      if context_mode_native_mcp_is_enabled; then
        print_check 'Native context MCP' 'enabled'
      else
        print_check 'Native context MCP' 'MISSING OR DISABLED'
        failed=true
      fi
    else
      print_check 'Context-mode plugin' 'NOT VERIFIED'
      failed=true
    fi
  fi

  if [[ -x $mobile_bin ]]; then
    mobile_version_output=$(CODEX_HOME=$codex_home "$mobile_bin" --version 2>/dev/null || printf 'unreadable')
    print_check 'Gestalt Mobile' "$mobile_version_output"
  else
    print_check 'Gestalt Mobile' 'MISSING'
    failed=true
  fi

  check_supervision_capability_coherence || failed=true
  run_doctor_command 'Optional skill collection' command_skills status || failed=true

  if command -v codex >/dev/null 2>&1; then
    run_doctor_command 'Codex doctor' run_codex_doctor || failed=true
  fi

  if [[ -n ${context_mode_runtime:-} && -f $context_mode_runtime/cli.bundle.mjs ]]; then
    run_doctor_command 'Context-mode doctor' \
      env CODEX_HOME="$codex_home" GESTALT_HOME="$gestalt_home" \
      CONTEXT_MODE_PLATFORM=codex CONTEXT_MODE_WORKSPACE="$PWD" \
      node "$context_mode_runtime/cli.bundle.mjs" doctor || failed=true
  fi

  run_doctor_command 'Bubblewrap and Codex sandbox' command_sandbox_doctor || failed=true

  if [[ -f $gestalt_home/serena/active.json ]]; then
    run_doctor_command 'Serena doctor' command_serena doctor || failed=true
  else
    print_check 'Serena' 'NOT INSTALLED (optional; gestalt serena install)'
  fi

  if [[ -f $gestalt_home/playwright/active.json ]]; then
    run_doctor_command 'Playwright doctor' command_playwright doctor || failed=true
  else
    print_check 'Playwright' 'NOT INSTALLED (optional; gestalt playwright install)'
  fi

  if "$failed"; then
    printf "\nDiagnostics reported a problem; follow the failing check's guidance above. Use 'gestalt install' or 'gestalt update' only for missing or incompatible managed components.\n" >&2
    return 1
  fi
  printf "\nAll startup diagnostics passed.\n"
}

main() {
  # Private, one-time continuation: skip only the completed manager download.
  # Keep the marker in argv rather than exporting it to installers or Mobile.
  if [[ ${1:-} == __updated-manager ]]; then
    manager_update_resumed=true
    shift
  fi
  local -a manager_invocation=("$@")
  local command_name=${1:-help}
  if (($# > 0)); then shift; fi

  validate_session_tmp_context
  load_paths
  case $command_name in
    install) command_install "$@" ;;
    agents) command_agents "$@" ;;
    update) command_update "$@" ;;
    update-restart) command_update_restart "$@" ;;
    __update-restart-worker) command_update_restart_worker "$@" ;;
    __codex-app-server) command_codex_app_server "$@" ;;
    __cli-owned) command_cli_owned "$@" ;;
    __scratch-hook) exec_node_program "$(session_scratch_runtime)" hook "$@" ;;
    scratch)
      if [[ ${1:-} == --help || ${1:-} == -h ]]; then
        printf '%s\n' 'Stop Mobile and all runtimes/tools using this owner before recovery.' \
          'gestalt scratch inspect --cwd ROOT --owner ID' \
          'gestalt scratch recover --cwd ROOT --owner ID --expect TOKEN --confirm-quiescent' \
          'Use the token from inspect. Only an empty Mobile containment fence is removed.' \
          'gestalt scratch inspect-tool-leases --cwd ROOT --owner ID' \
          'gestalt scratch recover-tool-leases --cwd ROOT --owner ID --expect TOKEN --confirm-quiescent' \
          'Use the token from inspect-tool-leases to release abandoned Mobile Serena/Playwright borrowers.' \
          'gestalt scratch inspect-publication --cwd ROOT' \
          'gestalt scratch recover-publication --cwd ROOT --expect TOKEN --confirm-quiescent' \
          'Use the token from inspect-publication to clear an abandoned empty workspace publication fence.' \
          'Never use these overrides on a live session. Payload and provider history are retained.'
      else
        require_command node
        exec_node_program "$(session_scratch_runtime)" scratch "$@"
      fi
      ;;
    cli) command_cli "$@" ;;
    mobile) command_mobile "$@" ;;
    xerj) die 'Xerj has been retired; run gestalt update to migrate managed configuration. User data is retained.' ;;
    serena) command_serena "$@" ;;
    playwright) command_playwright "$@" ;;
    path) command_path "$@" ;;
    skills) command_skills "$@" ;;
    skills-export) command_skills_export "$@" ;;
    skills-import) command_skills_import "$@" ;;
    doctor) command_doctor "$@" ;;
    version | --version | -V) command_version ;;
    help | --help | -h) usage ;;
    *) die "unknown command: $command_name (run 'gestalt help')" ;;
  esac
}

main "$@"
